面试经典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;
    }
};
相关推荐
三体世界19 分钟前
TCP传输控制层协议深入理解
linux·服务器·开发语言·网络·c++·网络协议·tcp/ip
你的冰西瓜37 分钟前
C++ 中最短路算法的详细介绍
c++·算法·图论·最短路
zstar-_43 分钟前
【算法笔记】6.LeetCode-Hot100-链表专项
笔记·算法·leetcode
Swift社区1 小时前
Swift 图论实战:DFS 算法解锁 LeetCode 323 连通分量个数
算法·swift·图论
<但凡.1 小时前
数据结构与算法之美:广义表
数据结构·c++·算法
前端极客探险家1 小时前
告别卡顿与慢响应!现代 Web 应用性能优化:从前端渲染到后端算法的全面提速指南
前端·算法·性能优化
程序员Xu2 小时前
【OD机试题解法笔记】连续出牌数量
笔记·算法·深度优先
CoovallyAIHub2 小时前
单目深度估计重大突破:无需标签,精度超越 SOTA!西湖大学团队提出多教师蒸馏新方案
深度学习·算法·计算机视觉
CoovallyAIHub2 小时前
从FCOS3D到PGD:看深度估计如何快速搭建你的3D检测项目
深度学习·算法·计算机视觉
偷偷的卷2 小时前
【算法笔记 day three】滑动窗口(其他类型)
数据结构·笔记·python·学习·算法·leetcode