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;
    }
};
相关推荐
小明说Java2 分钟前
常见排序算法的实现
数据结构·算法·排序算法
行云流水20191 小时前
编程竞赛算法选择:理解时间复杂度提升解题效率
算法
smj2302_796826522 小时前
解决leetcode第3768题.固定长度子数组中的最小逆序对数目
python·算法·leetcode
cynicme3 小时前
力扣3531——统计被覆盖的建筑
算法·leetcode
core5123 小时前
深度解析DeepSeek-R1中GRPO强化学习算法
人工智能·算法·机器学习·deepseek·grpo
mit6.8243 小时前
计数if|
算法
a伊雪4 小时前
c++ 引用参数
c++·算法
圣保罗的大教堂4 小时前
leetcode 3531. 统计被覆盖的建筑 中等
leetcode
Data_agent4 小时前
1688获得1688店铺列表API,python请求示例
开发语言·python·算法