6.Z字形变换

将字符串 "PAYPALISHIRING" 以Z字形排列成给定的行数:

P   A    H    N
A  P  L  S I  I   G
Y    I    R

之后从左往右,逐行读取字符:"PAHNAPLSIIGYIR"

示例1:
输入: s = "PAYPALISHIRING", numRows = 3
输出: "PAHNAPLSIIGYIR"

示例 2:
输入: s = "PAYPALISHIRING", numRows = 4
输出: "PINALSIGYAHRPI"

我自己感觉是V字形变换,就是找规律的题。

解法:按行访问
首先访问 行 0 中的所有字符,接着访问 行 1,然后 行 2,依此类推...

分析
  • 时间复杂度: O(n),其中 n == len(s)。每个索引被访问一次。
  • 空间复杂度: O(n),对于 C++ 实现,如果返回字符串不被视为额外空间,则复杂度为 O(1)

c++ code:

#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<sstream>
#include<assert.h>
using namespace std;


class Solution {
public:
    string convert(string s, int numRows) {
        if (numRows == 1)
            return s;
        string res;
        int len = s.size();
        int core = 2 * numRows - 2;
        for (int i = 0; i < numRows;i++)
        for (int j = 0; j + i < len; j += core)
        {
            res += s[j + i];
            //除了第一行和最后一行的规律
            if (i != 0 && i != numRows - 1 && j + core - i < len)
            {
                res += s[j + core - i];
            }

        }
        return res;
    }
};
 
int main() {
    string s; int numRows;
    cin >> s;
    cin >> numRows;
    string ret = Solution().convert(s,numRows);
    cout << ret;
    return 0;
}

参考1

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容