-
Notifications
You must be signed in to change notification settings - Fork 11
/
6. ZigZag Conversion.cpp
104 lines (88 loc) · 2.8 KB
/
6. ZigZag Conversion.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
//Runtime: 116 ms, faster than 8.32% of C++ online submissions for ZigZag Conversion.
//Memory Usage: 40 MB, less than 9.36% of C++ online submissions for ZigZag Conversion.
class Solution {
public:
string convert(string s, int numRows) {
if(numRows == 1) return s;
int n = s.size();
vector<vector<char>> zz(numRows, vector<char>(n, ' '));
int r = 0, c = 0;
//direction: false for down, true for up
bool d = false;
for(int i = 0; i < n; ++i){
// cout << "(" << r << ", " << c << ")" << endl;
zz[r][c] = s[i];
if(!d){
++r;
}else{
--r;
++c;
}
if(r == 0 || r == numRows-1)
d = !d;
}
string ans;
for(int r = 0; r < numRows; ++r){
for(int c = 0; c < n; ++c){
if(zz[r][c] != ' '){
ans += zz[r][c];
if(ans.size() == n) break;
}
}
if(ans.size() == n) break;
}
return ans;
}
};
//Approach 1: Sort by Row
//Runtime: 12 ms, faster than 99.63% of C++ online submissions for ZigZag Conversion.
//Memory Usage: 11 MB, less than 24.06% of C++ online submissions for ZigZag Conversion.
//time: O(N), space: O(N)
class Solution {
public:
string convert(string s, int numRows) {
if(numRows == 1) return s;
int n = s.size();
vector<string> rows(min(numRows,n));
int r = 0;
bool down = true;
for(char c : s){
rows[r] += c;
r += down ? 1 : -1;
if(r == 0 || r == numRows-1)
down = !down;
}
string ans;
for(string& row : rows){
ans += row;
}
return ans;
}
};
//Approach 2: Visit by Row
//Runtime: 12 ms, faster than 99.63% of C++ online submissions for ZigZag Conversion.
//Memory Usage: 8.6 MB, less than 58.45% of C++ online submissions for ZigZag Conversion.
//time: O(N), space: O(N)
class Solution {
public:
string convert(string s, int numRows) {
if(numRows == 1) return s;
int n = s.size();
int cycleLen = 2*(numRows - 1);
string ans;
/*
first row: k*cycleLen
last row: k*cycleLen+numRows-1
internal rows: k*cycleLen+i or (k+1)*cycleLen-i
*/
for(int i = 0; i < numRows; ++i){
for(int k = 0; i + k * cycleLen < n; ++k){
ans += s[i+k*cycleLen];
if(i != 0 && i != numRows-1 && (k+1)*cycleLen-i < n){
ans += s[(k+1)*cycleLen-i];
}
}
}
return ans;
}
};