6. 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)
字符串“PAYPALISHIRING”在以下给定数目的行上以Z字形图案书写:(您可能希望以固定字体显示该图案以便更好的易读性)
P A H N A P L S I I G Y I R
And then read line by line: "PAHNAPLSIIGYIR"
然后按行读"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"
.
#include<iostream> #include<set> #include<string> #include<vector> using namespace std; class Solution { public: string convert(string s, int numRows) { if (s.empty()) return ""; string result; int n = s.size(); int maxRow = (n / numRows ) * 2; if (numRows == 1 || maxRow == 0) { return s; } char **p = new char*[numRows]; for (int i = 0; i < numRows; i++) { p[i] = new char[maxRow]; memset(p[i], NULL, sizeof(char)*maxRow); } int *index = new int[numRows]; memset(index, 0, sizeof(int)*numRows); for (int i = 0; i < n; ) { for (int j = 0; j < numRows&&i < n; j++) { p[j][index[j]] = s[i++]; index[j]++; } for (int j = numRows-2; j >0 && i < n; j--) { p[j][index[j]] = s[i++]; index[j]++; } } for (int i = 0; i < numRows; i++) { for (int j = 0; j < maxRow; j++) { if (p[i][j] != NULL) result += p[i][j]; else break; } } return result; } }; int main() { Solution solution; string s = "A"; string result = solution.convert(s,2); cout << result; system("pause"); return 0; }
别人的代码
class Solution { public: string convert(string s, int numRows) { if(numRows == 1) return s; else{ int row = 0, step = 1; string *tmp = new string[numRows]; string rst; for(int i = 0; i < s.length(); ++i){ if(row == 0) step = 1; else if (row == numRows - 1) step = -1; tmp[row].push_back(s[i]); row += step; } for(int i = 0; i < numRows; ++i){ rst.append(tmp[i]); } return rst; } } };
class Solution { public: string convert(string s, int nRows) { if (nRows <= 1) return s; string res = ""; int size = 2 * nRows - 2; for (int i = 0; i < nRows; ++i) { for (int j = i; j < s.size(); j += size) { res += s[j]; int tmp = j + size - 2 * i; if (i != 0 && i != nRows - 1 && tmp < s.size()) res += s[tmp]; } } return res; } };