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)
And then read line by line: “PAHNAPLSIIGYIR”
Write the code that will take a string and make this conversion given a number of rows:
解法:找到每行的规律,按规律查找一行,以字符串长度为边界。
string ans;
int len = s.length();
int n=numRows;
if(n!=1){//当只有一行,直接输出
for (int i = 0; i < min(n,len); i++) {//当字符串的长度小于行数,取小的
int tmp = i;
ans += s[i];
if(len==1){//len=1 不需要查找
continue;
}
while (tmp < len) {
if ((n - i - 1) != 0) {//最后一项只有一位
tmp += 2 * (n - i - 1);
if (tmp < len) {//防越界
ans += s[tmp];
}
}
if (i != 0) {//第一项只有一位
tmp += i * 2;
if (tmp < len) {//每行按循环查找,不能超出界限
ans += s[tmp];
}
}
}
}}
else{
ans=s;//一行情况
}
return ans;
}