面试经典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;
    }
};
相关推荐
岁忧21 分钟前
(LeetCode 面试经典 150 题 ) 11. 盛最多水的容器 (贪心+双指针)
java·c++·算法·leetcode·面试·go
chao_78924 分钟前
二分查找篇——搜索旋转排序数组【LeetCode】两次二分查找
开发语言·数据结构·python·算法·leetcode
秋说2 小时前
【PTA数据结构 | C语言版】一元多项式求导
c语言·数据结构·算法
Maybyy3 小时前
力扣61.旋转链表
算法·leetcode·链表
谭林杰4 小时前
B树和B+树
数据结构·b树
卡卡卡卡罗特5 小时前
每日mysql
数据结构·算法
chao_7895 小时前
二分查找篇——搜索旋转排序数组【LeetCode】一次二分查找
数据结构·python·算法·leetcode·二分查找
蜉蝣之翼❉5 小时前
CRT 不同会导致 fopen 地址不同
c++·mfc
aramae6 小时前
C++ -- STL -- vector
开发语言·c++·笔记·后端·visual studio
lifallen6 小时前
Paimon 原子提交实现
java·大数据·数据结构·数据库·后端·算法