6. ZigZag Conversion

【题目】

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 s, int numRows);

Example 1:

Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"

Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:

P     I    N
A   L S  I G
Y A   H R
P     I

【题意】

字符串是zigzag形状/拉链形状来排列的(从左往右横着看),现在按行来读,获得新的string

【解答】

可以找到位置之间的规律,比如第一行的两个元素之间相差2*numRows-2。需要考虑的情况是,一列就可以完全排完和只有一行,此时直接return。

时间复杂度O(n),空间复杂度O(n)

【代码】

 1 class Solution {
 2 public:
 3     string convert(string s, int numRows) {
 4         int len = s.length();
 5         if(len <= numRows or numRows == 1) 
 6             return s;
 7         int diff = 2 * numRows - 2;
 8         string res = "";
 9         for(int row=0; row<numRows; row++){
10             res += s[row];
11             int nextPos = row + diff;
12             while(1){
13                 if(nextPos - 2*row >= len)
14                     break;
15                 if(row != 0 && row != (numRows - 1))
16                     res += s[nextPos - 2*row];
17                 if(nextPos < len){
18                     res += s[nextPos];
19                     nextPos += diff;
20                  }
21                  else
22                     break;
23             }
24         }
25         return res;
26     }
27 };

 

posted @ 2019-01-23 17:35  xxxinn  阅读(148)  评论(0)    收藏  举报