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;
    }
};
相关推荐
2301_81123298几秒前
低延迟系统C++优化
开发语言·c++·算法
alphaTao2 分钟前
LeetCode 每日一题 2026/1/26-2026/2/1
算法·leetcode
Christo323 分钟前
TFS-2026《Fuzzy Multi-Subspace Clustering 》
人工智能·算法·机器学习·数据挖掘
2401_8576835435 分钟前
C++中的原型模式
开发语言·c++·算法
s1hiyu1 小时前
C++动态链接库开发
开发语言·c++·算法
(❁´◡`❁)Jimmy(❁´◡`❁)1 小时前
CF2188 C. Restricted Sorting
c语言·开发语言·算法
We་ct1 小时前
LeetCode 54. 螺旋矩阵:两种解法吃透顺时针遍历逻辑
前端·算法·leetcode·矩阵·typescript
星火开发设计1 小时前
C++ 预处理指令:#include、#define 与条件编译
java·开发语言·c++·学习·算法·知识
mit6.8241 小时前
dijk|tire+floyd+dp %
算法
独自破碎E1 小时前
【总和拆分 + 双变量遍历】LCR_012_寻找数组的中心下标
数据结构·算法