本文共 1615 字,大约阅读时间需要 5 分钟。
class Solution {//be careful with the special case//when done with coding, figure out some cases (including illegal, normal, edge cases)//to run with this solution, this will help to get a bug-free solutionpublic: string convert(string s, int nRows) { // Start typing your C/C++ solution below // DO NOT write int main() function vector> zig(nRows, vector ()); int zigRow = 0; int sign = 1; for (int i = 0; i < s.size(); ++i) { zig[zigRow].push_back(s[i]); if (nRows == 1)//special case zigRow = 0; else { if(zigRow == nRows-1) sign = -1; if(zigRow == 0) sign = 1; zigRow += sign; } } string ans; for (int i = 0; i < zig.size(); ++i) { for (int j = 0; j < zig[i].size(); ++j) { ans.push_back(zig[i][j]); } } return ans; }};
second time
class Solution {public: string convert(string s, int nRows) { // Start typing your C/C++ solution below // DO NOT write int main() function if(nRows == 1) return s; string result; for(int i = 0; i < nRows; ++i) { int curOriginalIdx = i; int k = 0; while(curOriginalIdx < s.size()) { int nextOriginalIdx; if(k%2 == 0) nextOriginalIdx = curOriginalIdx+2*(nRows-1-i); else nextOriginalIdx = curOriginalIdx+2*(i); if(nextOriginalIdx != curOriginalIdx) result.push_back(s[curOriginalIdx]); curOriginalIdx = nextOriginalIdx; k++; } } return result; }};
转载地址:http://qhxti.baihongyu.com/