LeetCode 2075. 解码斜向换位密码(模拟)

简介: LeetCode 2075. 解码斜向换位密码(模拟)

文章目录


1. 题目


字符串 originalText 使用 斜向换位密码 ,经由 行数固定 为 rows 的矩阵辅助,加密得到一个字符串 encodedText 。

originalText 先按从左上到右下的方式放置到矩阵中。

image.png


先填充蓝色单元格,接着是红色单元格,然后是黄色单元格,以此类推,直到到达 originalText 末尾。

箭头指示顺序即为单元格填充顺序。所有空单元格用 ' ' 进行填充。

矩阵的列数需满足:用 originalText 填充之后,最右侧列 不为空 。


接着按行将字符附加到矩阵中,构造 encodedText 。


image.png

先把蓝色单元格中的字符附加到 encodedText 中,接着是红色单元格,最后是黄色单元格。箭头指示单元格访问顺序。


例如,如果 originalText = "cipher" 且 rows = 3 ,那么我们可以按下述方法将其编码:


image.png

蓝色箭头标识 originalText 是如何放入矩阵中的,红色箭头标识形成 encodedText 的顺序。在上述例子中,encodedText = "ch ie pr" 。


给你编码后的字符串 encodedText 和矩阵的行数 rows ,返回源字符串 originalText 。


注意:originalText 不 含任何尾随空格 ' ' 。生成的测试用例满足 仅存在一个 可能的 originalText 。


示例 1:

输入:encodedText = "ch   ie   pr", rows = 3
输出:"cipher"
解释:此示例与问题描述中的例子相同。

image.png

输入:encodedText = "iveo    eed   l te   olc", rows = 4
输出:"i love leetcode"
解释:上图标识用于编码 originalText 的矩阵。 
蓝色箭头展示如何从 encodedText 找到 originalText 。

image.pngimage.png

输入:encodedText = " b  ac", rows = 2
输出:" abc"
解释:originalText 不能含尾随空格,但它可能会有一个或者多个前置空格。
提示:
0 <= encodedText.length <= 10^6
encodedText 仅由小写英文字母和 ' ' 组成
encodedText 是对某个 不含 尾随空格的 originalText 的一个有效编码
1 <= rows <= 1000
生成的测试用例满足 仅存在一个 可能的 originalText


2. 解题


  • 按题意模拟即可
class Solution {
public:
    string decodeCiphertext(string encodedText, int rows) {
        int n = encodedText.size(), cols = n/rows;
        vector<vector<char>> mat(rows, vector<char>(cols));
        for(int i = 0; i < n; ++i)
            mat[i/cols][i%cols] = encodedText[i];
        string ans;
        for(int j = 0; j < cols; ++j)
        {
            int r = 0, c = j;
            while(r<rows && c<cols)
                ans += mat[r++][c++];//45度向下遍历
        }
        while(ans.size() && ans.back()==' ')
            ans.pop_back();//删除尾随空格
        return ans;
    }
};

112 ms 45 MB C++

相关文章
|
数据安全/隐私保护
【Leetcode -796.旋转字符串 -804.唯一摩尔斯密码词】
【Leetcode -796.旋转字符串 -804.唯一摩尔斯密码词】
46 0
|
2月前
|
算法 Python
【Leetcode刷题Python】百分号解码
深信服公司的算法笔试题.
34 1
|
4月前
|
存储 SQL 算法
优化解码方法:记忆化搜索和空间优化动态规划的实用指南 【LeetCode 题目 91】
优化解码方法:记忆化搜索和空间优化动态规划的实用指南 【LeetCode 题目 91】
|
5月前
动态规划之解码方法【LeetCode】
动态规划之解码方法【LeetCode】
|
5月前
leetcode-394:字符串解码
leetcode-394:字符串解码
51 0
|
5月前
|
Go
golang力扣leetcode 394.字符串解码
golang力扣leetcode 394.字符串解码
39 0
|
算法 数据安全/隐私保护 C语言
LeetCode每日一题2299. 强密码检验器 II
本题是一道LeetCode上的简单题,使用了模拟、位运算两种方法解题,各位看官往下看。
62 0
|
数据安全/隐私保护
LeetCode 1734. 解码异或后的排列
LeetCode 1734. 解码异或后的排列
74 0
LeetCode 394. 字符串解码
LeetCode 394. 字符串解码
99 0
LeetCode 394. 字符串解码
|
Python
LeetCode 394. 字符串解码
给定一个经过编码的字符串,返回它解码后的字符串。
91 0