leetcode

Leetcode Solutions (0x6A73)
git clone https://git.pngu.org/leetcode
Log | Files | Refs | Submodules | README

commit a938639a498879a8078db75a3e1ad060e574a021
parent d17fc79d3731489167a983ead40b150499cbd415
Author: Jack Sangdahl <jack@pngu.org>
Date:   Fri,  3 Apr 2026 20:42:10 -0600

2075. decode the slanted ciphertext

Diffstat:
Adecode_slanted_ciphertext.c | 46++++++++++++++++++++++++++++++++++++++++++++++
Adecode_slanted_ciphertext.py | 30++++++++++++++++++++++++++++++
2 files changed, 76 insertions(+), 0 deletions(-)

diff --git a/decode_slanted_ciphertext.c b/decode_slanted_ciphertext.c @@ -0,0 +1,46 @@ +// 2075. Decode the Slanted Ciphertext +#include "leetcode.h" + +/* + * 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'. given the encoded string 'encodedText' and a numbe of rows, return + * the original string 'originalText'. + */ + +char *decodeCiphertext(char *encodedText, int rows) { + if (rows == 1) + return strdup(encodedText); + int n = strlen(encodedText), cols = n / rows, idx = 0; + char *ans = (char *)malloc((n + 1) * sizeof(char)); + for (int c = 0; c < cols; c++) { + int r = 0, j = c; + while (r < rows && j < cols) { + ans[idx++] = encodedText[r * cols + j]; + r++; + j++; + } + } + while (idx > 0 && ans[idx - 1] == ' ') + idx--; + ans[idx] = '\0'; + return ans; +} + +int main() { + char *et1 = "ch ie pr"; + char *et2 = "iveo eed l te olc"; + char *et3 = "coding"; + char *dc1 = decodeCiphertext(et1, 3); + char *dc2 = decodeCiphertext(et2, 4); + char *dc3 = decodeCiphertext(et3, 1); + printf("%s\n", dc1); + assert(!strcmp(dc1, "cipher")); + printf("%s\n", dc2); + assert(!strcmp(dc2, "i love leetcode")); + printf("%s\n", dc3); + assert(!strcmp(dc3, "coding")); + free(dc1); + free(dc2); + free(dc3); +} diff --git a/decode_slanted_ciphertext.py b/decode_slanted_ciphertext.py @@ -0,0 +1,30 @@ +# 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'. given the encoded string 'encodedText' and a numbe of rows, return +the original string 'originalText'. +""" + + +class Solution: + def decodeCiphertext(self, encodedText: str, rows: int) -> str: + if rows == 1: + return encodedText + n, ans = len(encodedText), [] + cols = n // rows + for c in range(cols): + r, j = 0, c + while r < rows and j < cols: + ans.append(encodedText[r * cols + j]) + r += 1 + j += 1 + return "".join(ans).rstrip() + + +if __name__ == "__main__": + obj = Solution() + print(obj.decodeCiphertext(encodedText="ch ie pr", rows=3)) + print(obj.decodeCiphertext(encodedText="iveo eed l te olc", rows=4)) + print(obj.decodeCiphertext(encodedText="coding", rows=1))