Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit bd9b6f7

Browse files
authoredNov 17, 2021
Create decode-the-slanted-ciphertext.cpp
1 parent 74099be commit bd9b6f7

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
 

‎C++/decode-the-slanted-ciphertext.cpp

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
string decodeCiphertext(string encodedText, int rows) {
7+
const int cols = size(encodedText) / rows;
8+
int k = size(encodedText);
9+
for (int i = cols - 1; i >= 0 && k == size(encodedText); --i) {
10+
for (int j = i + ((size(encodedText) - 1) - i) / (cols + 1) * (cols + 1); j >= i; j -= cols + 1) {
11+
if (encodedText[j] != ' ') {
12+
k = j;
13+
break;
14+
}
15+
}
16+
}
17+
string result;
18+
for (int i = 0; i < cols && k != -1; ++i) {
19+
for (int j = i; j < size(encodedText); j += cols + 1) {
20+
result.push_back(encodedText[j]);
21+
if (j == k) {
22+
k = -1;
23+
break;
24+
}
25+
}
26+
}
27+
return result;
28+
}
29+
};
30+
31+
// Time: O(n)
32+
// Space: O(n)
33+
class Solution2 {
34+
public:
35+
string decodeCiphertext(string encodedText, int rows) {
36+
const int cols = size(encodedText) / rows;
37+
string result;
38+
for (int i = 0; i < cols; ++i) {
39+
for (int j = i; j < size(encodedText); j += cols + 1) {
40+
result.push_back(encodedText[j]);
41+
}
42+
}
43+
while (!empty(result) && result.back() == ' ') {
44+
result.pop_back();
45+
}
46+
return result;
47+
}
48+
};

0 commit comments

Comments
 (0)
Please sign in to comment.