-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZigZagConversion.cpp
More file actions
50 lines (47 loc) · 1.27 KB
/
Copy pathZigZagConversion.cpp
File metadata and controls
50 lines (47 loc) · 1.27 KB
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
40
41
42
43
44
45
46
47
48
49
50
#include <stdio.h>
#include <string>
using namespace std;
class Solution {
public:
string convert(string s, int nRows) {
if (nRows == 1) {
return s;
}
int unit_len = nRows + nRows - 2;
int step = s.length() / unit_len;
int remain = s.length() % unit_len;
if (remain > 0) {
step += 1;
}
string res = "";
for (int i = 0; i < nRows; i++) {
int offset = unit_len - i;
bool is_follow = offset < unit_len && offset >= nRows;
for (int j = 0; j < step; j++) {
int idx = i + j * unit_len;
if (idx < s.length()) {
res += s[idx];
} else {
break;
}
if (is_follow) {
idx = offset + j * unit_len;
if (idx < s.length()) {
res += s[idx];
} else {
break;
}
}
}
}
return res;
}
};
int main() {
Solution s;
string str = "PAYPALISHIRING";
string res = s.convert(str, 3);
printf("%s\n", res.c_str());
res = s.convert(str, 2);
printf("%s\n", res.c_str());
}