本文主要是介绍6. ZigZag Conversion--2016/10/10,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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”.
思路:找出排序后每行的规律,实际上是个数学问题
class Solution {
public:string convert(string s, int numRows) {int arraySize = 2 * (numRows-1);if (arraySize <= 0) {return s;}string result;for (int i = 0; i < numRows; i++) {for (int j = 0;; j++) {int index1 = j*arraySize + i;if (index1 < s.size()) {result += s[index1];if (i == 0 || i == numRows - 1) {continue;}int index2 = index1 + arraySize - (i << 1);// (j + 1)*arraySize - i;if (index2 < s.size()) {result+=s[index2];}else {break;}}else{break;}}}return result;}
};
这篇关于6. ZigZag Conversion--2016/10/10的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!