LeetCode_6_ZigZag Conversion

LeetCode 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)
Alt text

And then read line by line: “PAHNAPLSIIGYIR”

Write the code that will take a string and make this conversion given a number of rows:

1
string convert(string s, int numRows);

样例如下

Example 1:

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

Example 2:

1
2
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"

Explanation:
Alt text

解题思路:

弄一个numRows * s.length()的数组,便利s,按规律插入就行了

代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
public:
string convert(string s, int numRows) {
int len = s.length();
vector<vector<char> > ss(numRows,vector<char>(len, '0'));
int i, j;
if(len == 0) return "";
if(numRows == 1) return s;
ss[0][0] = s[0];
int count = 0;
bool spe = false;
int x = 0;
int y = 0;
for(i = 1; i < len; i++) {
if(!spe) {
x++;
ss[x][y] = s[i];
//cout << x << " " << y << " " << ss[x][y] << endl;
} else {
x--, y++;
ss[x][y] = s[i];
//cout << x << " " << y <<" " << ss[x][y] << endl;
}
count++;
if(count == numRows-1) {
count = 0;
spe = !spe;
}
}
string re;
for(i = 0; i < numRows; i++) {
for(j = 0; j <= y; j++) {
if(ss[i][j] != '0') re.push_back(ss[i][j]);
//cout << ss[i][j ] << endl;
}
}
return re;
}
};