题目链接

  题目要求:

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

  为了解决这道题,我们再举一个例子:

  LeetCode之“字符串”:ZigZag Conversion

  如果我们把上图稍微转变一下:

  LeetCode之“字符串”:ZigZag Conversion

  也就是说,其实我们可以把中间斜线处的字母移到他们左边竖线字母下边,这样就更方便我们用二维矩阵来表示了。因此,我们可以将输入字符串分为等长的几个部分,不足的补充特别字符,如下图:

  LeetCode之“字符串”:ZigZag Conversion

  根据这种想法写出来的程序如下:

 1 class Solution {
 2 public:
 3     string convert(string s, int numRows) {
 4         int szS = s.size();
 5         if(szS == 0 || numRows < 2 || szS <= numRows)
 6             return s;
 7         
 8         int nRows = numRows + numRows - 2;
 9         int nCols = szS / nRows + 1;
10         vector<vector<char> > matrix(nRows, vector<char>(nCols, '#'));
11         int k = 0;
12         for(int j = 0; j < nCols; j++)
13             for(int i = 0; i < nRows; i++)
14             {
15                 if(k < szS)
16                 {
17                     matrix[i][j] = s[k];
18                     k++;
19                 }
20             }
21              
22         string retStr;
23         for(int i = 0; i < numRows; i++)
24             for(int j = 0; j < nCols; j++)
25                 if(i == 0 || i == numRows - 1)
26                 {
27                     if(matrix[i][j] != '#')
28                         retStr += matrix[i][j];
29                 }
30                 else
31                 {
32                     if(matrix[i][j] != '#')
33                         retStr += matrix[i][j];
34                     if(matrix[nRows - i][j] != '#')
35                         retStr += matrix[nRows - i][j];
36                 }
37         
38         return retStr;
39     }
40 };
View Code

相关文章:

  • 2022-01-16
  • 2021-09-30
  • 2021-12-01
  • 2021-09-27
  • 2021-10-03
  • 2020-06-10
  • 2019-09-09
  • 2021-11-27
猜你喜欢
  • 2021-08-21
  • 2021-08-21
  • 2018-04-06
  • 2020-04-27
  • 2021-11-09
  • 2021-08-17
  • 2021-04-16
  • 2018-09-02
相关资源
相似解决方案