【LeetCode006算法/编程练习C++】ZigZag Conversion //折形string重新排序
2016-12-22 17:00
441 查看
6. ZigZag Conversion
Total Accepted: 126488Total 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; } };
运行结果:
祝刷题愉快~
感谢苹果精神上以及猪肉脯肉体上对于本题的支持…(刷题刷得好饿……)
相关文章推荐
- c++ 选择排序 练习
- C++实现数组的排序/插入重新排序/以及逆置操作
- c++ 选择排序 练习
- C++实现数组的排序/插入重新排序/以及逆置操作
- 【LeetCode014-015算法/编程练习C++】最长共同前缀,3Sum(和为0) //用到了map的自动排序
- C++基础算法练习之排序比较
- linux下练习 c++ 库函数排序使用举例
- 【C++练习】排序
- 【C++的探索路13】继承与派生之练习篇(需重新学习)
- 蓝桥杯练习系统-数列排序 C++
- c++ 选择排序 练习
- 重新再学习C++的练习
- C++实现数组的排序/插入重新排序/以及逆置操作详解
- C++实现单链表按k值重新排序的方法
- 在c++中qsort()排序函数的使用qsort函数应用大全
- (原創) 如何列出一篇文章的所有單字並依size和字母順序排序? (初級) (C++)
- c++实现合并排序
- [C#]练习了下数组和类,C++ 基础还算可以,不是很吃力
- 重新学习C++
- 重新温习数据结构二:简单排序