您的位置:首页 > 编程语言 > C语言/C++

Leetcode 6. ZigZag Conversion

2016-04-21 21:59 429 查看
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"
.

核心思想:找出循环单元 如上面的例子 当nRows是时,原串的每个字符对应的行数为 1 2 3 2 1 2 3 2 1 2 3 2 1 2 ,很容易看出循环结构为 1 2 3 2 长度为:2*3-2

代码如下:

class Solution {
public:
string convert(string s, int numRows) {
if(numRows==1||s=="")
return s;
string ss[numRows];//用来存储相应行号的串
int flag;//用来存储原串字母对应行号
for(int i=0;i<s.size();i++){
flag=(i+1)%(2*numRows-2);
if(flag>numRows)
flag=2*numRows-flag;
if(flag==0)
flag=2;
ss[flag-1]+=s[i];
}
string ans;
for(int i=0;i<numRows;i++)
ans+=ss[i];
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Leetcode ZigZag string C++