题意:
将字符串
"PAYPALISHIRING"以Z字形排列成给定的行数:numRows=3
思路:
1.当空字符或者只有一个字符的时候直接输出字符;
2.
P
A
H N 按如图所示的颜色将字符分组,每一组字符长度num1=numRows*2-2
A
P
L
S
I
I G 总共可以分几组num=s.size()/num1或者num=s.size()/num1+1
Y
I
R
3.按规律输出字符
代码如下:
class Solution {
public: string convert(string s, int numRows) {
string result;
int num1 = numRows * 2 - 2;
if(s.size()<2||num1==0){
result=s;
return result;
}
int num = (s.size() / num1)+1;
if(s.size()%num1==0) num = (s.size() / num1);
string str[100];
int count = 0;
int i = 0;
for (int j = 0; j < s.size(); j++){
if (count == num1){
i++;
count = 0;
}
str[i].push_back(s[j]);
count++;
}//存储num组的字符,就是按照上述颜色分类存入过渡数组
//按规律输出字符
for (int n = 0; n < num; n++) {
result.push_back(str[n][0]);
}
for (int m = 1; m < numRows; m++){
for (int n = 0; n < num; n++) {
if (m < str[n].size()) result.push_back(str[n][m]);
if ((num1 - m) < str[n].size() && m != (num1 - m)) result.push_back(str[n][num1 - m]);
}
}
return result;
}
};