Leetcode 2075. Decode the Slanted Ciphertext

Problem

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.

Algorithm

Store the letters in a matrix and read them diagonally from left to right to form words.

Code

python3 复制代码
class Solution:
    def decodeCiphertext(self, encodedText: str, rows: int) -> str:
        if not encodedText:
            return ""

        cols = len(encodedText) // rows
        mat = [['' for _ in range(cols)] for _ in range(rows)]
        for r in range(rows):
            for c in range(cols):
                mat[r][c] = encodedText[r * cols + c]
        
        ans = []
        for col in range(cols):
            r, c = 0, col
            while r < rows and c < cols:
                ans.append(mat[r][c])
                r += 1
                c += 1
        
        return "".join(ans).rstrip()
相关推荐
大熊背28 分钟前
ISP图像处理中大数乘法溢出处理(一)
人工智能·python·算法·溢出处理
wabs6661 小时前
关于栈【力扣1047. 删除字符串中的所有相邻重复项的思考】
数据结构·c++·算法·leetcode··代码随想录
疯狂打码的少年1 小时前
【数据结构】选择类排序:简单选择与堆排序
java·数据结构·笔记·算法
晚风醉蝶2 小时前
1-16-计数排序-CountingSort
python·算法·排序算法
疯狂打码的少年2 小时前
【数据结构】排序算法:归并排序与基数排序
数据结构·笔记·算法·排序算法
ychqsq2 小时前
122.收网
经验分享·职场和发展
fb_123452 小时前
Shell 脚本从 0 到精通|脚本规范 + 变量 + 数值运算 + 条件测试(可直接复制,面试必备)
chrome·面试·职场和发展
吃旺旺雪饼的小男孩2 小时前
U-Net 语义分割详解:原论文、PyTorch 实现与真实消融实
人工智能·pytorch·python·算法
lucas_AI2 小时前
35 种开源文档抽取配置,只有 4 个跨过 F1 0.5
人工智能·算法·llm
YSoup2 小时前
2026 安卓面试助手APP(安卓八股、题库)
android·面试·职场和发展