将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 "PAYPALISHIRING" 行数为 3 时,排列如下:
P A H N
A P L S I I G
Y I R
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"PAHNAPLSIIGYIR"。
请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
1.找规律 会发现从上到下从左到右每两个间隔首先是是2*n-2*i,其次间隔是2*i
2.最后一行单独拿出来处理
class Solution {
public:
string convert(string s, int n) {
if(n == 1) return s;
int len = s.length();
string ans="";
int tmp = 2*n;
for(int i=0; i<n-1; i++) {
tmp -= 2;
int cnt = 0;
for(int j=i; j<len; j+=tmp) {
ans += s[j];
if(cnt) {
// cout<< "before:" << j << ans << endl;
j += 2*i;
if(j<len&&i) ans += s[j];
// cout<< "after:" << j << " " <<ans << endl;
}
cnt++;
}
// cout << ans << endl;
}
//最后一行
for(int i=n-1; i<len; i+=2*n-2) {
ans += s[i];
}
return ans;
}
};