当前位置: 首页 > news >正文

面试经典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

二、题解

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

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;}
};
http://www.lryc.cn/news/207733.html

相关文章:

  • for循环三种跳出循环的方法(retrun、continue、break)
  • React中的受控组件(controlled component)和非受控组件(uncontrolled component)
  • python 查找波峰和波谷
  • 深入理解 Document Load 和 Document Ready 的区别
  • 有趣的算法(七) ——快速排序改进算法
  • Vue3 + Tsx 集成 ace-editor编辑器
  • TypeScritpt中的namespace
  • LeetCode75——Day17
  • Spring中Bean的作用域
  • 什么是命令行参数解析和选项处理?
  • 网络协议--TFTP:简单文件传送协议
  • MongoDB 的集群架构与设计
  • volatile 系列之实现原理
  • 【黑马程序员】mysql进阶篇笔记
  • A - Block Sequence
  • 0031【Edabit ★☆☆☆☆☆】【使用箭头函数】Using Arrow Functions
  • C#,数值计算——分类与推理,基座向量机(SVM,Support Vector Machines)的计算方法与源程序
  • 面试总结之消息中间件
  • Java零基础入门-逻辑运算符
  • 图的应用3.0-----拓扑排序
  • Unity之ShaderGraph如何实现冰冻效果
  • 解决 viteprees 中 vp-doc 内置样式影响组件预
  • flask 和fastdeploy 快速部署 yolov3
  • Go 反射
  • 竞赛选题 深度学习卷积神经网络垃圾分类系统 - 深度学习 神经网络 图像识别 垃圾分类 算法 小程序
  • ts-node模块
  • 【VUE】ElementPlus之动态主题色调切换(Vue3 + Element Plus+Scss + Pinia)
  • MySQL数据库基本操作1
  • Webpack简介及打包演示
  • 面向对象设计模式——命令模式