forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
decode-the-slanted-ciphertext.cpp
48 lines (46 loc) · 1.35 KB
/
decode-the-slanted-ciphertext.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
// Time: O(n)
// Space: O(1)
class Solution {
public:
string decodeCiphertext(string encodedText, int rows) {
const int cols = size(encodedText) / rows;
int k = size(encodedText);
for (int i = cols - 1; i >= 0 && k == size(encodedText); --i) {
for (int j = i + ((size(encodedText) - 1) - i) / (cols + 1) * (cols + 1); j >= i; j -= cols + 1) {
if (encodedText[j] != ' ') {
k = j;
break;
}
}
}
string result;
for (int i = 0; i < cols && k != -1; ++i) {
for (int j = i; j < size(encodedText); j += cols + 1) {
result.push_back(encodedText[j]);
if (j == k) {
k = -1;
break;
}
}
}
return result;
}
};
// Time: O(n)
// Space: O(n)
class Solution2 {
public:
string decodeCiphertext(string encodedText, int rows) {
const int cols = size(encodedText) / rows;
string result;
for (int i = 0; i < cols; ++i) {
for (int j = i; j < size(encodedText); j += cols + 1) {
result.push_back(encodedText[j]);
}
}
while (!empty(result) && result.back() == ' ') {
result.pop_back();
}
return result;
}
};