FANGYEFENG

Mar 05, 2024

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);

Solution 1

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
string convert(string s, int numRows) {
if(numRows==1) return s;
string ans;
for(int i=0;i<numRows;i++){
int step=(numRows-1)*2;
int substep=step-i*2;
int j=i;
while(j<s.size()){
ans.push_back(s[j]);
j+=substep;
if(j>=s.size()) break;
if(substep!=0 && substep!=step) ans.push_back(s[j]);
j+=step-substep;
}
}
return ans;
}
};
OLDER > < NEWER