[LeetCode] ZigZag Converesion 之字型转换字符串

时间:2022-09-26 11:56:45

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

这道题刚开始看了半天没看懂是咋样变换的,上网查了些资料,终于搞懂了,就是要把字符串摆成一个之字型的,比如有一个字符串 "0123456789ABCDEF",转为 zigzag 如下所示:

当 n = 2 时:

0 2 4 6 8 A C E

1 3 5 7 9 B D F

当 n = 3 时:

0   4    8     C

1 5 9 B D F

2    6   A     E

当 n = 4 时:

0     6        C

1   7   B  D

2   8 A    E

3      9       F

可以发现,除了第一行和最后一行没有中间形成之字型的数字外,其他都有,而首位两行中相邻两个元素的 index 之差跟行数是相关的,为  2*nRows - 2, 根据这个特点,可以按顺序找到所有的黑色元素在元字符串的位置,将他们按顺序加到新字符串里面。对于红色元素出现的位置(Github 上可能无法正常显示颜色,请参见博客园上的帖子)也是有规律的,每个红色元素的位置为 j + 2 x numRows-2 - 2 x i, 其中,j为前一个黑色元素的 index,i为当前行数。 比如当 n = 4 中的那个红色5,它的位置为 1 + 2 x 4-2 - 2 x 1 = 5,为原字符串的正确位置。知道了所有黑色元素和红色元素位置的正确算法,就可以一次性的把它们按顺序都加到新的字符串里面。代码如下:

解法一:

class Solution {
public:
string convert(string s, int numRows) {
if (numRows <= ) return s;
string res;
int size = * numRows - , n = s.size();
for (int i = ; i < numRows; ++i) {
for (int j = i; j < n; j += size) {
res += s[j];
int pos = j + size - * i;
if (i != && i != numRows - && pos < n) res += s[pos];
}
}
return res;
}
};

若上面解法中的规律不是很好想的话,我们也可以用下面这种更直接的方法来做,建立一个大小为 numRows 的字符串数组,为的就是把之字形的数组整个存进去,然后再把每一行的字符拼接起来,就是想要的结果了。顺序就是按列进行遍历,首先前 numRows 个字符就是按顺序存在每行的第一个位置,然后就是 ‘之’ 字形的连接位置了,可以发现其实都是在行数区间 [1, numRows-2] 内,只要按顺序去取字符就可以了,最后把每行都拼接起来即为所求,参见代码如下:

解法二:

class Solution {
public:
string convert(string s, int numRows) {
if (numRows <= ) return s;
string res;
int i = , n = s.size();
vector<string> vec(numRows);
while (i < n) {
for (int pos = ; pos < numRows && i < n; ++pos) {
vec[pos] += s[i++];
}
for (int pos = numRows - ; pos >= && i < n; --pos) {
vec[pos] += s[i++];
}
}
for (auto &a : vec) res += a;
return res;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/6

类似题目:

Zigzag Iterator

Binary Tree Zigzag Level Order Traversal

参考资料:

https://leetcode.com/problems/zigzag-conversion/

https://www.cnblogs.com/springfor/p/3889414.html

https://leetcode.com/problems/zigzag-conversion/discuss/3403/Easy-to-understand-Java-solution

https://leetcode.com/problems/zigzag-conversion/discuss/3417/A-10-lines-one-pass-o(n)-time-o(1)-space-accepted-solution-with-detailed-explantation

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] ZigZag Converesion 之字型转换字符串的更多相关文章

  1. &lbrack;LeetCode&rsqb; 6&period; ZigZag Converesion 之字型转换字符串

    The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like ...

  2. &lbrack;LeetCode&rsqb; 6&period; ZigZag Conversion 之字型转换字符串

    The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like ...

  3. LeetCode OJ:ZigZag Conversion(字符串的Z字型转换)

    The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like ...

  4. leetcode 6&sol;300 Z字型变换 py

    目录 题目说明 方法一:利用flag 题目说明 方法一:利用flag 简单来说就是利用flag来表示方向,真的神来之笔. class Solution: def convert(self, s: st ...

  5. 281&period; Zigzag Iterator z字型遍历

    [抄题]: Given two 1d vectors, implement an iterator to return their elements alternately. Example: Inp ...

  6. 剑指offer从上往下打印二叉树 、leetcode102&period; Binary Tree Level Order Traversal&lpar;即剑指把二叉树打印成多行、层序打印)、107&period; Binary Tree Level Order Traversal II 、103&period; Binary Tree Zigzag Level Order Traversal&lpar;剑指之字型打印&rpar;

    从上往下打印二叉树这个是不分行的,用一个队列就可以实现 class Solution { public: vector<int> PrintFromTopToBottom(TreeNode ...

  7. 算法:Z字型(Zigzag)编排

    问题:给定 n 行和 m 列的二维数组矩阵.如图所示,以 ZIG-ZAG 方式打印此矩阵. 从对称的角度来看,通过反复施加滑行反射可以从简单的图案如线段产生规则的之字形. 主要思想:算法从(0, 0) ...

  8. lintcode:Matrix Zigzag Traversal 矩阵的之字型遍历

    题目: 矩阵的之字型遍历 给你一个包含 m x n 个元素的矩阵 (m 行, n 列), 求该矩阵的之字型遍历. 样例 对于如下矩阵: [ [1, 2, 3, 4], [5, 6, 7, 8], [9 ...

  9. PHP中IP地址与整型数字互相转换详解

    这篇文章主要介绍了PHP中IP地址与整型数字互相转换详解,本文介绍了使用PHP函数ip2long与long2ip的使用,以及它们的BUG介绍,最后给出自己写的两个算法,需要的朋友可以参考下 IP转换成 ...

随机推荐

  1. MySQL入门01-MySQL源码安装

    操作系统:CentOS 6.7 MySQL版本:5.6.30 1.前期准备 2.系统配置 3.CMake编译配置 4.make && make install 5.后期配置和测试 Re ...

  2. Java字节数组转按radix进制输出

    代码如下: public class Main_bytesToStr { public static void main(String[] args) throws IOException { // ...

  3. NPOI Helper文档

    public class ExcelHelper { /// <summary> /// NPOI Excel转DataTable /// </summary> /// &lt ...

  4. Mysql --分区表&lpar;2&rpar;

    分区类型 RANGE分区 range分区的表是利用取值范围将数据分成分区,区间要连续并且不能互相重叠,使用values less than操作符进行分区定义 LIST分区 LIST分区是建立离散的值列 ...

  5. BZOJ 1002 &lbrack;FJOI2007&rsqb;轮状病毒

    1002: [FJOI2007]轮状病毒 Time Limit: 1 Sec  Memory Limit: 162 MBSubmit: 3106  Solved: 1724[Submit][Statu ...

  6. 弹出层之2:JQuery&period;BlockUI

    JQuery.BlockUI是众多JQuery插件弹出层中的一个,它小巧(原版16k,压缩后10左右),容易使用, 功能齐全,支持Iframe,支持Modal,可定制性高也意味他默认谦虚的外表. jQ ...

  7. FliterLog代码分析

    Filter简介 Filter也称之为过滤器,它是Servlet技术中最实用的技术,WEB开发人员通过Filter技术,对web服务器管理的所有web资源:例如Jsp, Servlet, 静态图片文件 ...

  8. 07Axios

    详情:https://pizzali.github.io/2018/10/30/Axios/ JQuery时代,我们使用ajax向后台提交数据请求,Vue时代,Axios提供了前端对后台数据请求的各种 ...

  9. winform 窗体关闭枚举类

    switch (e.CloseReason) { case CloseReason.None: break; case CloseReason.WindowsShutDown: break; case ...

  10. &lbrack;NOI&period;AC&rsqb;COUNT&lpar;数学&rpar;

    解析: 也可以将所有的可能都计算出来,后进行减法运算. 代码: #include<bits/stdc++.h> using namespace std; #define ll long l ...