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()
相关推荐
想做小南娘,发现自己是女生喵1 小时前
【无标题】
数据结构·算法
Kx_Triumphs3 小时前
HDU4348 To the moon(主席树区间修改模板)
算法·题解
旖-旎3 小时前
《LeetCode647 回文子串 || LeetCode 5 最长回文子串》
c++·算法·leetcode·动态规划·哈希算法
轻颂呀4 小时前
约瑟夫环问题
算法
科技大视界6 小时前
投资AI项目,传统尽调不够用了——李章虎律师拆解算法、数据、算力三大雷区
人工智能·算法·数据挖掘
郝学胜-神的一滴6 小时前
算法实战:最小k个数——大顶堆的优雅解法
开发语言·数据结构·c++·python·程序人生·算法·排序算法
Irissgwe6 小时前
算法滑动窗口
数据结构·算法
怪兽学LLM6 小时前
LeetCode 105. 从前序与中序遍历序列构造二叉树:分治递归思路详解
算法·leetcode·职场和发展
可编程芯片开发6 小时前
基于PI控制的三相整流器控制系统的simulink建模与仿真,包含超级电容充电和电机
算法