您的位置:首页 > 其它

[leetcode 6] ZigZag Conversion

2015-12-11 08:36 417 查看
Question:

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"
.

分析:
上图例子中下标顺序为:

04812
135791113
2610
可以看出一个规律就是第0行和第nRows-1行的下标间隔是一样的,为interval = 2*nRows-2;中间行的下标是跳跃的,依次为 interval - 2*i;2*i;interval - 2*i;2*i。。。
所以返回的字符串为nRows个字符串串联的结果;

代码如下:

class Solution {
public:
string convert(string s, int numRows) {
string result = "";
int interval = 2 * numRows - 2;
int len = s.size();
if(len <= numRows || numRows == 1)
return s;
for(int i = 0; i < numRows; ++i){
int pos = i;
if(i == 0 || i == numRows-1){
while(pos < len){
result += s[pos];
pos += interval;
}
}
else{
int b = 2 * i;
while(pos < len){
result += s[pos];
b = interval - b;
pos += b;
}
}
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: