题目: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".
思路:
本题的一个思路就是一行一行的判断,对于有多少行,计算出gap=2*n-1;每一行i=i+gap;直接可以输出。
但是要注意的一点就是在另外一边的一个数字的计算,当然首先需要判断不能超过n。
还有一点就是第一行和最后一行不需要判断。
代码:
class Solution {
public:
string convert(string s, int numRows) {
int len=s.length();
if(numRows==1||len<=numRows){//还没有numRows大,直接从上往下读
return s;
}
string result;
int gap=2*numRows-2;
for(int i=0;i<numRows;i++){
for(int j=i;j<len;j=j+gap){
result.push_back(s[j]);
if(i>0&&i<numRows-1&&(j+gap-2*i)<len){
result.push_back(s[j+gap-2*i]);
}
//除去第一行和最后一行,第二列之字形的数字
}
}
return result;
}
};