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;
    }
};
相关推荐
youngee1117 小时前
hot100-60子集
数据结构·算法
郝学胜-神的一滴18 小时前
Linux线程属性设置分离技术详解
linux·服务器·数据结构·c++·程序人生·算法
Timmylyx051818 小时前
2025年最后一搏—— Educational Codeforces Round 186 (Rated for Div. 2) 题解
算法·codeforces·比赛日记
微光闪现18 小时前
国际航班动态提醒与延误预测优选平台指南
大数据·人工智能·算法
leoufung18 小时前
LeetCode 120. Triangle:从 0 分到 100 分的思考过程(含二维 DP 与空间优化)
linux·算法·leetcode
gihigo199818 小时前
基于反步法的路径追踪控制
算法
Jim-2ha018 小时前
【JavaScript】常见排序算法实现
javascript·算法·排序算法
王老师青少年编程18 小时前
2025年12月GESP(C++二级): 黄金格
c++·算法·gesp·csp·信奥赛·二级·黄金格
Herbert_hwt18 小时前
C语言位操作符详解:从入门到实战应用
c语言·算法
ss27319 小时前
CompletionService:Java并发工具包
java·开发语言·算法