我这里的思想是,设置一个string数组,数组里边的每一个string字符串代表的是每一行的元素。因为给出的string字符串里边的元素,假设给的numRows=3,那么元素依次存放的行数是1、2、3、2、1、2、3、2、、、、两个周期,一个1、2,一个3、2。
假设给出的numRows=4,那么元素依次在的行数是:1、2、3、4、3、2、1、2、3、4、3、2、、、也是两个周期,一个是1、2、3,一个是4、3、2.
所以总结一下,string的元素依次在的行数是1…numRows-1;以及numRows…2
依次遍历string里边的元素,设置两个for循环来表示两个行数周期,将元素依次放在string字符串数组里边。string字符串数组也是从1开始的,存放的是第一行的字符。
最后遍历string字符串数组,1到numRows行,就是最后的字符串
class Solution {
public:
string convert(string s, int numRows) {
if (s.length() == 1||numRows==1)
return s;
const int n = 1000;
string a[n];
int len = s.length();
int i = 0;
while(i<len) {
for (int j = 1; j < numRows; j++) {
if (i < len) {
a[j] = a[j] + s[i];
i++;
}
else
break;
}
for (int z = numRows; z > 1; z--) {
if (i < len) {
a[z] = a[z] + s[i];
i++;
}
else
break;
}
}
string res;
for (int k = 1; k <= numRows; k++) {
res = res + a[k];
}
return res;
}
};