Decode the Slanted Ciphertext LeetCode solution in C++

1
class Solution {
2
public:
3
string decodeCiphertext(string encodedText, int rows) {
4
int n = encodedText.size();
5

6
// Determining the number of columns
7
int cols = n / rows;
8
vector<vector<char>> mat(rows, vector<char>(cols, ' '));
9
int i = 0, j = 0;
10
int k = 0;
11

12
string ans = "";
13

14
// Filling the matrix using encodedText
15
// Row wise
16
for (int i = 0; i < rows; i++) {
17
for (int j = 0; j < cols; j++) {
18
mat[i][j] = encodedText[k++];
19
}
20
}
21

22
// Only the upper triangular part of the matrix will
23
// contain characters of the originalText
24
// so, this loop traverses that area
25
for (int k = 0; k < n - (rows * (rows - 1)) / 2; k++) {
26
// i, j are the two pointers for tracking rows and columns
27
ans.push_back(mat[i++][j++]);
28

29
// If any boundary is hit, then column pointer is subtracted
30
// by row_pointer - 1
31
// and row pointer is reset to 0
32
if (i == rows || j == cols) {
33
j -= (i - 1);
34
i = 0;
35
}
36
}
37

38
// Removing all trailing spaces
39
while (ans.back() == ' ') ans.pop_back();
40

41
return ans;
42
}
43
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0