题目来源:https://leetcode.com/problems/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 text, int nRows);

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

 

解题思路:

 

Zigzag:即循环对角线结构(

 

0       8       16      
1     7 9     15 17      
2   6   10   14   18      
3 5     11 13     19      
4       12       20      

 

给出代码:

 1 class Solution {
 2 public:
 3     string convert(string s, int nRows){
 4     if(nRows == 1) return s;
 5     string res[nRows];
 6     int i = 0, j, gap = nRows-2;
 7     while(i < s.size()){
 8         for(j = 0; i < s.size() && j < nRows; ++j) res[j] += s[i++];
 9         for(j = gap; i < s.size() && j > 0; --j) res[j] += s[i++];
10     }
11     string str = "";
12     for(i = 0; i < nRows; ++i)
13         str += res[i];
14     return str;
15     }
16 };

 

相关文章:

  • 2021-07-16
  • 2021-06-16
  • 2021-10-25
  • 2021-12-26
  • 2022-03-10
  • 2021-12-19
  • 2021-06-18
  • 2021-11-03
猜你喜欢
  • 2021-03-31
  • 2022-01-15
  • 2021-04-09
  • 2021-10-07
  • 2022-01-09
  • 2021-07-24
相关资源
相似解决方案