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,依此类推...

7432549-17de675dc64510c1.png

分析

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值