面试经典150题——Day22

文章目录

一、题目

6. Zigzag Conversion

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P A H N

A P L S I I G

Y I R

And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

string convert(string s, int numRows);

Example 1:

Input: s = "PAYPALISHIRING", numRows = 3

Output: "PAHNAPLSIIGYIR"

Example 2:

Input: s = "PAYPALISHIRING", numRows = 4

Output: "PINALSIGYAHRPI"

Explanation:

P I N

A L S I G

Y A H R

P I

Example 3:

Input: s = "A", numRows = 1

Output: "A"

Constraints:

1 <= s.length <= 1000

s consists of English letters (lower-case and upper-case), ',' and '.'.

1 <= numRows <= 1000

题目来源: leetcode

二、题解

找到字符串的周期规律,构建对应的字符串数组,

cpp 复制代码
class Solution {
public:
    string convert(string s, int numRows) {
        int n = s.length();
        if(numRows == 1) return s;
        int reminder = 2 * numRows - 2;
        vector<string> rowString(numRows,"");
        for(int i = 0;i < n;i++){
            int mod = i % reminder;
            if(mod < numRows - 1) rowString[mod] += s[i];
            else rowString[numRows - 1 - (mod - numRows + 1)] += s[i];
        }
        string res = "";
        for(int i = 0;i < numRows;i++){
            res += rowString[i];
        }
        return res;
    }
};
相关推荐
进击的荆棘34 分钟前
优选算法——滑动窗口
c++·算法·leetcode
csdn_aspnet40 分钟前
奈飞工厂算法:个性化推荐系统的极限复刻
算法·netflix·奈飞
小白_ysf41 分钟前
Vue 中常见的加密方法(对称、非对称、杂凑算法)
前端·vue.js·算法
多米Domi0112 小时前
0x3f 第49天 面向实习的八股背诵第六天 过了一遍JVM的知识点,看了相关视频讲解JVM内存,垃圾清理,买了plus,稍微看了点确定一下方向
jvm·数据结构·python·算法·leetcode
_F_y8 小时前
MySQL用C/C++连接
c语言·c++·mysql
兩尛8 小时前
c++知识点2
开发语言·c++
xiaoye-duck8 小时前
C++ string 底层原理深度解析 + 模拟实现(下)——面试 / 开发都适用
开发语言·c++·stl
Azure_withyou9 小时前
Visual Studio中try catch()还未执行,throw后便报错
c++·visual studio
琉染云月9 小时前
【C++入门练习软件推荐】Visual Studio下载与安装(以Visual Studio2026为例)
c++·visual studio
L_090710 小时前
【C++】高阶数据结构 -- 红黑树
数据结构·c++