2075.解码斜向换位密码

https://leetcode-cn.com/problems/decode-the-slanted-ciphertext/

观察+坐标变换

解码过程为几条对角线,坐标为

第一条对角线:(0,0)--(1,1)--...--(row-1, row-1)

第二条对角线:(0,1)--(1,2)--...--(row-1, row)

。。。

第col条

甚至不用构建矩阵,用二维坐标转一维的辅助函数,直接从encodedText读取即可

class Solution:
    def decodeCiphertext(self, encodedText: str, rows: int) -> str:
        l = len(encodedText)
        cols = l // rows
        def flat(x, y):		#二维坐标转为一维
            return x * cols + y
        res = ''
        for  j in range(cols):
            for k in range(rows):
                if j+k< cols and k < rows:
                    res += encodedText[flat(k, j+k)] 
        return res.rstrip()		#最后记得删除右侧多余的空格

最后更新于