File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments