题目:
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"
.
解题思路:
ZigZag折线
- 如果nRows = 1时,convert返回:
P A Y P A L I S H I R I N G - 如果nRows=2时,convert返回:
P Y A I H R N A P L S I I G - 如果nRows=4时,convert返回:
使用稀疏矩阵的方法可以存储每个字符。返回时按行装入string类容P I N A L S I G Y A H R P I #include <iostream> #include <string> #include <list> using namespace std; class Solution { public: string convert(string s, int nRows) { ELE *p = new ELE[s.size()]; int flag = 1; string res; int temp = 0; for (int i = 0; i < s.size() && nRows != 1;) { if (flag) { while (temp < nRows && i < s.size()) { p[i].ele = s[i]; p[i].row = temp++; i++; } flag = (flag + 1) % 2; } else { temp -= 2; while (temp > 0 && i < s.size()) { p[i].ele = s[i]; p[i].row = temp--; i++; } flag = (flag + 1) % 2; } } /* 这部分代码可以优化,创建nRows个List, 每个List存放数组中的行,那么装入string类容器时只需要遍历s.size(),
整个程序的算法复杂就会降为O(s的长度) */ int k = 0; for (int i = 0; i < nRows && nRows != 1; i++) //每行一次入容器 { for (int j = 0; j < s.size(); j++)//将第i行入容器 { if (p[j].row == i) res += p[j].ele; //cout << p[j].ele; } } if (nRows == 1) res = s; return res; } private: typedef struct //稀疏矩阵方法 { char ele; int row; // int col; } ELE; }; int main() { class Solution s; string ttt("PAYPALISHIRING"); string ans; ans = s.convert(ttt, 3); cout << ans << endl; return 0; }