您的位置:首页 > 其它

LeetCode 6. ZigZag Conversion 解题报告

2016-09-01 00:27 375 查看


题目描述:

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

解题思路:

  本题题意为以z字形格式排列的字符串逐行读出来。由于行数不确定,所以使用vector相对于数组来说更方便一些。使用一个bool变量odd来标记此时字符向下排列(如)还是斜向上方排列。

P
4000
A   H   N
A P L S I I G
Y   I   R              p->A->Y即为odd为真时向下排列

 向下排列

P   A   H   N
A P L S I I G
Y   I   R              Y->P->A为斜向上排列。但是此时Y和A分别被包含在前两个向下的排列中。P则在odd为假时被加入第二行。

斜向上排列

代码展示

#include <iostream>
#include <string>
#include <vector>
class Solution {
public:
string convert(string s, int numRows)
{
vector<char> tmp;
vector<vector<char> > res;
for(int i=0 ; i<numRows ; i++)
{
res.push_back(tmp);
}
bool flag =false;
//int jj =0;
bool odd = true;//odd 标记序列向下移动
for(int i=0 ; i<s.size()&&!flag;)
{
if(odd)
{
for(int j=0; j<numRows ;j++)
{
res[j].push_back(s[i]);
i++;
if(i==s.size())
{
flag = true;
break;
}

}
odd = !odd;
}
else
{
for(int j=numRows-2; j>0 ;j--)
{
res[j].push_back(s[i]);
i++;
if(i==s.size())
{
flag = true;
break;
}

}
odd = !odd;
}

}
string ans;
for(int i=0;i<res.size();i++)
{
for(int j=0 ; j<res[i].size();j++)
ans+=res[i][j];
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: