-
Notifications
You must be signed in to change notification settings - Fork 3
/
6.cpp
56 lines (52 loc) · 1.49 KB
/
6.cpp
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
51
52
53
54
55
56
class Solution {
public:
int modifyLoopIdx(int loopIdx, int numRows) {
if (loopIdx >= numRows) {
return numRows * 2 - 2 - loopIdx;
}
return loopIdx;
}
string convert(string s, int numRows) {
if (numRows == 1) return s;
vector<string> zigzag(numRows, "");
int loop = numRows * 2 - 2;
int loopIndex = 0;
for (auto c : s) {
zigzag[modifyLoopIdx(loopIndex, numRows)].push_back(c);
loopIndex++;
if (loopIndex == loop) loopIndex = 0;
}
string res;
for (auto& str : zigzag) res += str;
return res;
}
};
// v2
class Solution {
public:
string convert(string s, int numRows) {
if (numRows == 1) return s;
int n = s.size();
int cycle = (numRows - 1) * 2;
string out;
for (int i = 0; i < numRows; ++i) {
int start = i;
if (start == 0 || start == numRows - 1) {
while (start < n) {
out.push_back(s[start]);
start += cycle;
}
}
else {
int counter = cycle - start;
while (start < n || counter < n) {
if (start < n) out.push_back(s[start]);
if (counter < n) out.push_back(s[counter]);
start += cycle;
counter += cycle;
}
}
}
return out;
}
};