[LeetCode]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)
P A H N
A P L S I I G
Y I R
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 convert(string text, int nRows);
convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.
寻找数学规律,类似于将字符串按照蛇形的顺序读,然后按照正常的顺序输出,读取时每次的步长大小为2*(numRows-1),且还需注意,若不是首尾两行,每次跳步中有与其对称的点。时间复杂度是O(n)
class Solution {
public:
string convert(string s, int numRows) {
if(s.length()<numRows||numRows<2)
return s;
string result = s;
int steplength = 2*(numRows-1),k=0;
for(int i=0;i<numRows;i++){
for(int j=i;j<s.length();j+=steplength){
result[k++]=s[j];
if((i!=0)&&(i!=numRows-1)&&(j+steplength-2*i<s.length()))
result[k++]=s[j+steplength-2*i];
}
}
return result;
}
};
2万+




被折叠的 条评论
为什么被折叠?



