ZigZag Conversion
Dec 6 '11
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 RAnd 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"
.
总感觉写的很2b。
class Solution { public: string convert(string s, int nRows) { int size = s.size(); if (size == 0) return s; if (nRows == 1) return s; string tmp; tmp.resize(size); std::vector<int> ls(nRows); int step = 2 * nRows - 2; int rows = size / step; int left = size - rows * step; ls[0] = rows + (left > 0 ? 1 : 0); ls[nRows - 1] = rows + (left > nRows - 1 ? 1 : 0); for (int i = 1; i < nRows - 1; ++i) { ls[i] = 2 * rows + (left > i ? 1 : 0); } if (left - nRows > 0) { int t = left - nRows; int c = nRows - 2; while (t-- > 0) { ls[c--]++; } } std::vector<int> offset(nRows, 0); for (int i = 1; i < nRows; ++i) { offset[i] = offset[i-1] + ls[i-1]; } for (int i = 0; i < rows; ++i) { for (int j = 0; j < nRows; ++j) { tmp[offset[j]++] = s[i*step + j]; } for (int j = 0; j < nRows-2; ++j) { int l = nRows - 2 - j; tmp[offset[l]++] = s[i*step+nRows+j]; } } for (int i = 0; i < min(left, nRows); ++i) { tmp[offset[i]++] = s[rows*step+i]; } if (left > nRows) { for (int i = 0; i < left-nRows; ++i) { tmp[offset[nRows-2-i]++] = s[rows*step+nRows+i]; } } return tmp; } };
又写了一遍~
class Solution { public: string convert(string s, int nRows) { if (nRows == 1) return s; int len = s.size(); if (len == 0) return string(); int step = nRows + nRows - 2; int parts = len / step; int left = len - parts * step; vector<int> l(nRows, parts); for (int i = 1; i < nRows - 1; i++) l[i]+=parts; if (left > nRows) { for (int i = 0; i < nRows; i++) l[i]++; left -= nRows; for (int i = nRows - 2; left >0 && i >= 0; i--, left--) l[i]++; } else { for (int i = 0; left >0 && i < nRows; i++, left--) l[i]++; } vector<int> idx(nRows, 0); idx[0] = 0; for (int i = 1; i < nRows ; i++) idx[i] = idx[i-1] + l[i-1]; string res; res.resize(len); int r = 0; bool down = true; for (int i = 0; i < len; i++) { res[idx[r]++] = s[i]; if (down) { if (r == nRows-1) { r--; down = false; } else r++; } else { if (r == 0) { r++; down = true; } else r--; } } return res; } };