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;
    }
};
相关推荐
ysu_03146 小时前
05 | 持久化撤销提示非核心功能
算法·游戏程序
浮沉9878 小时前
二分查找算法概述&通用模板
算法
Keven_119 小时前
算法札记:SPFA判负环算法的证明
算法
什巳9 小时前
JAVA练习278- 和为 K 的子数组
java·学习·算法·leetcode
Jerry9 小时前
LeetCode 347. 前 K 个高频元素
算法
Young Doro10 小时前
SAC 算法
线性代数·算法·机器学习
罗超驿10 小时前
2.算法效率的核心密码:时间复杂度和空间复杂度详解
java·数据结构·算法
:-)10 小时前
算法-堆排序
数据结构·算法·排序算法