您的位置:首页 > 其它

LeetCode | 6. ZigZag Conversion 循环技巧题

2018-01-30 16:50 85 查看
Thestring "PAYPALISHIRING" is written in a zigzag pattern on
a given number of rows likethis: (you may want to display this pattern in a fixed font for betterlegibility)

P   A   H   N

A P L S I I G

Y   I   R

And then read line by line: "PAHNAPLSIIGYIR"

Writethe code that will take a string and make this conversion given a number ofrows:

string convert(string text, int nRows);

convert("PAYPALISHIRING",3) should return "PAHNAPLSIIGYIR".

字符串技巧题,只需要将给定的字符串按照列的方向输入string数组,然后按照行的方向输出string数组就能得到最终的结果class Solution {
public:
string convert(string s, int numRows) {
if (numRows == 1) return s;
int index=0, c=0;
int n = s.size();
vector<string> theMark(numRows,"");
while (index < n)
{
while (c < numRows&&index < n)
{
theMark[c++].push_back(s[index++]);
}
c -= 2;
while (c >= 1&&index < n)
{
theMark[c--].push_back(s[index++]);
}
}
string result = "";
for (int i = 0; i < numRows; i++)
{
result.append(theMark[i]);
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: