您的位置:首页 > 其它

Leetcode#6 ZigZag Conversion

2015-06-24 22:13 429 查看
Difficulty EasyThe 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"
class Solution {
public:
string convert(string s, int numRows) {int j = 0, len = s.length(),coun=0;
if(numRows==1||len==1)
return s;
string ans;
while(j<len)
{
ans =ans + s[j];
j = j + 2*numRows -2;}if(len>=2)
{
for(int i=1;i<=(numRows-2);i++)
{
int k =i;
while(k<len){
ans=ans + s[k];
k = k + 2*(numRows-1-i);if(k<len)
ans=ans + s[k];
else
break;
k = k + 2*i;}}}if(len>=numRows&&len!=1){
j = numRows - 1;
while(j<len)
{
ans=ans+ s [j];
j = j + 2*numRows -2;}
}cout<<ans<<endl;
return ans;
}};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: