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

【LeetCode006算法/编程练习C++】ZigZag Conversion //折形string重新排序

2016-12-22 17:00 441 查看


6. ZigZag Conversion

Total Accepted: 126488
Total Submissions: 490130
Difficulty: Easy
Contributors: Admin

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

--------------------------题目解释-----------------------------------

首先解释下ZigZag,大概就是下面这样的……//复制的维基百科的

详情见:链接





也就是把string的顺序重新排列下,需要注意的是中间有反向……

可运行通过的代码如下:

class Solution {
public:
string convert(string s, int numRows) {

int one = 2 * numRows - 2;
if (numRows == 1)one = 1;
int rows = s.size() / one;
int left = s.size() % one;
vector<string>package;
string result = "";
for (int i = 0; i<rows; i++)
package.push_back(s.substr(i*one, one));
if (left != 0)package.push_back(s.substr(one*rows, left));

for (int j = 0; j < numRows; j++) {
for (int i = 0; i < rows+1 ; i++) {
if (j == 0) { if (i < rows || j < left) result += package[i][0]; }
else if (j == numRows - 1) {if (i < rows || j < left) result += package[i][numRows - 1];
}
else {
if (i<rows )
{
result += package[i][j];
result += package[i][one - j];
}
if (i==rows&&left!=0&&j<left){
result += package[i][j];
if (left-numRows>numRows-j-2)result += package[i][one - j];
}
}
}
}
return result;
}
};


运行结果:



祝刷题愉快~

感谢苹果精神上以及猪肉脯肉体上对于本题的支持…(刷题刷得好饿……)

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: