-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path6. Zigzag Conversion
35 lines (29 loc) · 1.02 KB
/
6. Zigzag Conversion
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
class Solution {
public:
string convert(string s, int numRows) {
if (numRows == 1) {
return s;
}
string answer;
int n = s.size();
int charsInSection = 2 * (numRows - 1);
for (int currRow = 0; currRow < numRows; ++currRow) {
int index = currRow;
while (index < n) {
answer += s[index];
// If currRow is not the first or last row
// then we have to add one more character of current section.
if (currRow != 0 && currRow != numRows - 1) {
int charsInBetween = charsInSection - 2 * currRow;
int secondIndex = index + charsInBetween;
if (secondIndex < n) {
answer += s[secondIndex];
}
}
// Jump to same row's first character of next section.
index += charsInSection;
}
}
return answer;
}
};