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()
相关推荐
BD4SXV3 分钟前
线性二次调节器(Linear Quadratic Regulator,LQR)的无限时域最优控制求解与黎卡提方程
算法·自动化
ST——Jess12 分钟前
2026年度传统文化数字化与命理科技(Ethno-tech)行业趋势研究报告:专业级数智工作台的技术壁垒与评测标准
人工智能·科技·算法·架构
Matrix_1134 分钟前
第13篇:非线性位移场——漩涡、鱼眼、水波纹与球面化
图像处理·算法
金牌归来发现妻女流落街头36 分钟前
【LeetCode 第207题】
算法·leetcode·拓扑·领接表
熬夜敲代码的猫42 分钟前
AVL树(C++详解版)
数据结构·c++·算法
-To be number.wan1 小时前
算法日记 | STL-MAP
c++·算法
cjp5601 小时前
015. UG 二次开发,拉伸草图生成实体类,高级草图类封装
算法
Eric 辰东1 小时前
【C 语言程序的编译和链接】详解编译链接过程
c语言·笔记·算法·学习方法
迈巴赫车主1 小时前
蓝桥杯21247弹跳鞋java
java·开发语言·数据结构·算法·职场和发展·蓝桥杯
jghhh012 小时前
基于 Weiler-Atherton 算法的多边形裁剪程序实现
算法