面试经典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;
    }
};
相关推荐
会编程的土豆3 分钟前
leetcode hot 100 之哈希
算法·leetcode·哈希算法
秋天的一阵风3 分钟前
【LeetCode 刷题系列|第 3 篇】详解大数相加:从模拟竖式到简洁写法的优化之路🔢
前端·算法·面试
qwehjk20087 分钟前
分布式计算C++库
开发语言·c++·算法
m0_716765237 分钟前
C++提高编程--仿函数、常用遍历算法(for_each、transform)详解
java·开发语言·c++·经验分享·算法·青少年编程·visual studio
_深海凉_13 分钟前
LeetCode热题100-反转链表
python·leetcode·链表
寻寻觅觅☆14 分钟前
东华OJ-基础题-59-倒数数列(C++)
开发语言·c++·算法
我不是懒洋洋15 分钟前
【数据结构】顺序表专题(详细代码及配图)
c语言·开发语言·数据结构·算法·青少年编程·visual studio
Trouvaille ~17 分钟前
【优选算法篇】BFS 解决最短路——寻找最优路径的真谛
c++·算法·leetcode·面试·蓝桥杯·宽度优先·最短路问题
雅俗共赏10023 分钟前
医学图像重建中常用的迭代求解器分类
图像处理·算法
不熬夜的熬润之29 分钟前
KCF算法解析
人工智能·算法·计算机视觉·机器人