面试经典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;
    }
};
相关推荐
道影子1 分钟前
《道德经》031兵者不祥,胜以丧礼处之
人工智能·深度学习·算法
花生了什么事o5 分钟前
分布式 ID 生成方案:从数据库自增到雪花算法
数据库·分布式·算法
king_linlin5 分钟前
算法基础——算法复杂度
c语言·开发语言·数据结构·算法
此生决int1 小时前
深入理解C++系列(04)——类和对象(下)
开发语言·c++
king_linlin1 小时前
数据结构——顺序表(附图文讲解|超详细)
c语言·数据结构·算法
GAOJ_K1 小时前
老旧产线弧形导轨换新:同规格替换避坑选型思路
人工智能·算法·机器学习·制造·导轨偏磨
Jerry6 小时前
LeetCode 189. 轮转数组
算法
Jerry6 小时前
LeetCode 739. 每日温度
算法
2601_9545267511 小时前
【工业传感与算法实战】温漂补偿与零点抗漂破局:基于二阶多项式拟合的 C/C++ 边缘校准算法,深度拆解“压力变送器什么牌子好”的技术硬指标
c语言·c++·算法
code_pgf12 小时前
`unordered_map` 详解
c++