[LeetCode] Decode the Slanted Ciphertext

2075. Decode the Slanted Ciphertext

A string originalText is encoded using a slanted transposition cipher to a string encodedText with the help of a matrix having a fixed number of rows rows.

originalText is placed first in a top-left to bottom-right manner.

The blue cells are filled first, followed by the red cells, then the yellow cells, and so on, until we reach the end of originalText. The arrow indicates the order in which the cells are filled. All empty cells are filled with ‘ ‘. The number of columns is chosen such that the rightmost column will not be empty after filling in originalText.

encodedText is then formed by appending all characters of the matrix in a row-wise fashion.

The characters in the blue cells are appended first to encodedText, then the red cells, and so on, and finally the yellow cells. The arrow indicates the order in which the cells are accessed.

For example, if originalText = “cipher” and rows = 3, then we encode it in the following manner:

The blue arrows depict how originalText is placed in the matrix, and the red arrows denote the order in which encodedText is formed. In the above example, encodedText = “ch ie pr”.

Given the encoded string encodedText and number of rows rows, return the original string originalText.

Note: originalText does not have any trailing spaces ‘ ‘. The test cases are generated such that there is only one possible originalText.

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
class Solution {
string parse(vector<vector<char>>& A, int p) {
int i = 0, j = p;
int n = A.size(), m = A[0].size();
string res = "";
while(i < n and j < m) {
res.push_back(A[i++][j++]);
}
return res;
}
public:
string decodeCiphertext(string s, int rows) {
if(rows == 1) return s;
int n = s.length();
vector<vector<char>> A(rows, vector<char>(n / rows));
for(int i = 0, k = 0; i < rows; i++) {
for(int j = 0; j < n / rows; j++) {
A[i][j] = s[k++];
}
}
string res = "";
for(int i = 0; i < n / rows; i++) {
res += parse(A, i);
}
while(!res.empty() and res.back() == ' ') res.pop_back();
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/23/PS/LeetCode/decode-the-slanted-ciphertext/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.