目录
1,题目描述
英文描述
中文描述
2,解题思路
4,解题过程
1,题目描述
英文描述
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
中文描述
将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下:
L C I R
E T O E S I I G
E D H N
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"。
请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
示例 1:
输入: s = "LEETCODEISHIRING", numRows = 3
输出: "LCIRETOESIIGEDHN"
示例 2:
输入: s = "LEETCODEISHIRING", numRows = 4
输出: "LDREOEIIECIHNTSG"
解释:
L D R
E O E I I
E C I H N
T S G
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zigzag-conversion
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2,解题思路
参考@力扣 (LeetCode)【Z 字形变换】,方法简单而且清晰,和螺旋矩阵那题(@&再见萤火虫&【LeetCode_Array_54. Spiral Matrix (C++)】)有异曲同工之妙。
主要思想有两点:
1,如何表示结果字符串?
- 使用string类型的vector,每个string变量表示一行,numRows即容器中string的个数(当题目给出的字符串中字符个数小于numRows时,可以选择较小的那个)。这样遍历一次源字符串s,可以将属于哪一行的字符方便的添加到vector中对应字符串后面rows[curRow] += c,最后将容器中各个字符串按行依次拼接即可;
2,如何遍历源字符串s,获得Z字形结果?
- 使用变量curRow表示当前行,整型变量flag表示下一行的方向是向上(-1),还是向下(+1)。那么下一行的行数就是curRow + flag;
- 每次curRow到达0或curRow-1时,对flag取反,即可完成Z字型遍历;
3,AC代码(C++)
4,解题过程
没有想到合适的算法,直接欣赏官方答案了。简单清晰!