Difficulty: Easy算法
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"
.this
class Solution { public: string convert(string s, int numRows) { } };
難度係數:簡單
字符串"PAYPALISHIRING"被以給定行的曲折形式寫成了下面的樣子:(有時候爲了方便閱讀你可能須要以固定的字體寫成這種樣子) 注:從上往下再從下往上讀再翻譯
P A H N A P L S I I G Y I R
若是一行一行的讀應該是 "PAHNAPLSIIGYIR"
code
要求:接收一個字符串,以給定的行數轉換成Z形字符串:string convert(string text, int nRows);
convert("PAYPALISHIRING", 3)
應返回 "PAHNAPLSIIGYIR"
。leetcode
此題理解題意重要。 每一行對應一個字符串,遍歷原字符串,而後把相應的字符加到對應行的字符串。字符串
class Solution { public: string convert(string s, int numRows) { int size = static_cast<int>(s.size()); // 當行數小於等於1 或 大於原串的size時不用轉換 if (numRows <= 1 || numRows >= size) { return s; } // 字符串數組, 裝的是行的對應的字符串 vector <string> rowString(numRows); int rowNum = 1; // 向下讀仍是向上讀的標誌 int flag = 1; for (int i = 0; i < size; ++i) { rowString[rowNum-1] += s[i]; if (rowNum == numRows){ flag = -1; } if (rowNum == 1) { flag = 1; } rowNum += flag; } string result; for (int i = 0; i < numRows; ++i) { result += rowString[i]; } return result; } };