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()
相关推荐
普通攻击往后拉8 小时前
Leetcode 206. 反转链表
算法·leetcode·链表
@syh.9 小时前
【贪心】矩阵消除游戏
算法·游戏·矩阵
可编程芯片开发9 小时前
基于零极点配置的PID控制系统simulink建模与仿真
算法
徐小夕10 小时前
开源!我用SQLite + DuckDB打造了一款可视化AI问数平台
前端·算法·github
Hrain-AI10 小时前
2026 企业 AI 智能体平台横评:8 大主流平台 7 维度实测对比
人工智能·算法·机器学习
Angel Q.11 小时前
因子分析和生成模型有什么关系?从“幕后因素”到“生成数据”
算法
咩咩啃树皮12 小时前
第52篇:前端工程化完整体系精讲——Vite构建、模块化、打包原理、规范体系、面试终极通关
前端·面试·职场和发展
FBI HackerHarry浩12 小时前
AI大模型开发V2第四阶段线性回归
人工智能·算法·线性回归
Jerry14 小时前
LeetCode 108. 将有序数组转换为二叉搜索树
算法