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;
    }
};
相关推荐
不会写DN7 小时前
为什么map查找时间复杂度是O(1)?
算法·哈希算法·散列表
始三角龙7 小时前
LeetCode hoot 100 -- 找到字符串中的所有字母异位词
算法·leetcode·职场和发展
abant27 小时前
leetcode 45 跳跃问题2 很难的贪心
算法·leetcode·职场和发展
小糯米6017 小时前
C语言指针3
c语言·数据结构·算法
ZPC82107 小时前
ROS2 通信提速快过UDP
人工智能·算法·机器人
RD_daoyi7 小时前
谷歌2026年 3 月核心更新深度解析:SEO 从内容优化到信息供给系统的全面重构
人工智能·算法·重构
lkforce7 小时前
MiniMind学习笔记(零)--基础概念
人工智能·算法·机器学习·token·分词器·minimind·词汇表
6Hzlia7 小时前
【Hot 100 刷题计划】 LeetCode 94. 二叉树的中序遍历 | C++ 递归法 & 迭代法
算法
nike0good7 小时前
The 4th Universal Cup GP of Kyoto, April 4-5, 2026 题解
算法·深度优先·图论
澈2078 小时前
高效查找算法详解:从顺序到哈希
数据结构·算法·哈希算法