ZigZag Conversion
The string "PAYPALISHIRING"
is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N A P L S I I G Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3)
should return "PAHNAPLSIIGYIR"
.
思路:
通过取模运算把字母放在相应的位置上。这里做了一些变通。
题解:
class Solution { public: string convert(const string& s, int nrows) { const size_t STRLEN = s.size(); string result; int modulus = nrows * 2 - 2; if (modulus == 0) return result = s; // 0th row for (int i = 0; i < STRLEN; i += modulus) result.push_back (s[i]); // rows without skip for (int j = 1; j < modulus / 2; ++j) for (int i = 0; i < STRLEN; i += modulus) { if (i + j < STRLEN) result.push_back (s[i + j]); int oppo = i + modulus - j; if (oppo < STRLEN) result.push_back (s[oppo]); } // last row for (int i = nrows - 1; i < STRLEN; i += modulus) result.push_back (s[i]); return result; } };