leetcode 面试150之 Z 字形变换

将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列

比如输入字符串为 "PAYPALISHIRING" 行数为 3 时,排列如下:

复制代码
P   A   H   N
A P L S I I G
Y   I   R

这里我们可以准备numRows个string对象来接受s中的字符

可以看到上述例子的插入规律是

3行:0 1 2 1

4行:0 1 2 3 2 1

5行:0 1 2 3 4 3 2 1

这里我们可以准备一个数组然后按照规律数组去插入相应的stirng对象

完整代码:

cpp 复制代码
class Solution {
public:
    string convert(string s, int numRows) {
        string val="";
        vector<int> index;
        vector<string> dp(numRows,"");
        int len=s.length();
        
        /*获取规律数组*/
        for(int i=0;i<numRows;i++)  index.push_back(i);
        int temp=numRows-2;
        while(temp>=1)  {index.push_back(temp);temp--;}
        
        /*遍历s  插入其归属string*/
        for(int i=0;i<len;i++)                          
        {
           dp[index[i%index.size()]]+=s[i];              
        }   
        
        for(auto ie:dp)
        {
           val+=ie;
        }  
        return val;
    }
};
相关推荐
Frostnova丶8 小时前
【算法笔记】数学知识
笔记·算法
吴可可1238 小时前
AutoCAD 2016与2014二次开发关键差异
算法
雨白9 小时前
哈希:以时间换空间的算法实战
算法
San813_LDD11 小时前
[数据结构]LeetCode学习
数据结构·算法·图论
x1387028595711 小时前
c语言排雷游戏(基础版9*9)
c语言·算法·游戏
sheeta199812 小时前
LeetCode 每日一题笔记 日期:2026.06.06 题目:2196. 根据描述创建二叉树
笔记·算法·leetcode
小欣加油12 小时前
leetcode994 腐烂的橘子
数据结构·c++·算法·leetcode·bfs
QuZero13 小时前
Guava Cache Deep Dive
java·后端·算法·guava
随意起个昵称13 小时前
线性dp-LIS题目4(A Twisty Movement)
算法·动态规划