/**
* Problem: LeetCode 2075 - Decode the Slanted Ciphertext
* Difficulty: Medium
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public String decodeCiphertext(String encodedText, int rows) {
if (rows == 1 || encodedText == null || encodedText.isEmpty()) {
return encodedText;
}
int n = encodedText.length();
int cols = n / rows;
StringBuilder sb = new StringBuilder(n);
for (int c = 0; c < cols; c++) {
for (int r = 0; r < rows && c + r < cols; r++) {
sb.append(encodedText.charAt(r * cols + (c + r)));
}
}
int len = sb.length();
while (len > 0 && sb.charAt(len - 1) == ' ') {
len--;
}
sb.setLength(len);
return sb.toString();
}
}
"""
Problem: LeetCode 2075 - Decode the Slanted Ciphertext
Difficulty: Medium
Language: Python
Author: CodeByTushu
"""
class Solution:
def decodeCiphertext(self, encodedText: str, rows: int) -> str:
"""
Decodes a slanted transposition ciphertext matrix back into originalText.
Time Complexity: O(N)
Space Complexity: O(N)
"""
if rows == 1 or not encodedText:
return encodedText
n = len(encodedText)
cols = n // rows
res = []
for c in range(cols):
for r in range(rows):
if c + r >= cols:
break
res.append(encodedText[r * cols + (c + r)])
return "".join(res).rstrip(" ")
/**
* Problem: LeetCode 2075 - Decode the Slanted Ciphertext
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
#include <string>
using namespace std;
class Solution {
public:
string decodeCiphertext(string encodedText, int rows) {
if (rows == 1 || encodedText.empty()) {
return encodedText;
}
int n = encodedText.size();
int cols = n / rows;
string res = "";
res.reserve(n);
for (int c = 0; c < cols; c++) {
for (int r = 0; r < rows && c + r < cols; r++) {
res += encodedText[r * cols + (c + r)];
}
}
while (!res.empty() && res.back() == ' ') {
res.pop_back();
}
return res;
}
};
/**
* Problem: LeetCode 2075 - Decode the Slanted Ciphertext
* Difficulty: Medium
* Language: JavaScript
* Author: CodeByTushu
*/
var decodeCiphertext = function(encodedText, rows) {
if (rows === 1 || !encodedText) {
return encodedText;
}
const n = encodedText.length;
const cols = Math.floor(n / rows);
const res = [];
for (let c = 0; c < cols; c++) {
for (let r = 0; r < rows && c + r < cols; r++) {
res.push(encodedText[r * cols + (c + r)]);
}
}
while (res.length > 0 && res[res.length - 1] === ' ') {
res.pop();
}
return res.join('');
};