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)
PAHN A P L S I I G YIR
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 text, int nRows);
convert("PAYPALISHIRING", 3)
should return "PAHNAPLSIIGYIR"
.题意:将一个字符串按给定行数蜿蜒排列,返回排列后按行输出的字符串。
我觉得这题的关键点在于弄清楚zigzag pattern的含义,下面我画图先解释一下:
(设输入字符串s="abcdefghijklmn……")
1、若nRows=1,则排列格式为abcdefghijklmn...;
2、若nRows=2,则排列格式为
![leetcode|【Leetcode】ZigZag Conversion](https://img.it610.com/image/info8/e5118acc91124416a8c688e064afed59.jpg)
文章图片
3、若nRows=3,则排列格式为
![leetcode|【Leetcode】ZigZag Conversion](https://img.it610.com/image/info8/7078276ff5f047e4b171235e52c3ee11.jpg)
文章图片
4、若nRows=4,则排列格式为
![leetcode|【Leetcode】ZigZag Conversion](https://img.it610.com/image/info8/3583637a35a749f8aaf39036ade5eec2.jpg)
文章图片
5、若nRows=5,6,7....同理
由上我们可以观察到,这个排列是是有规律可循的,当nRows=1,2时,字符串以原本的顺序排列和插空排列。
【leetcode|【Leetcode】ZigZag Conversion】nRows>2时,每个循环的元素个数为2(nRows-1)。因此,我们可以建立一个动态数组vector,里面包含nRows个
string类型的元素,然后对字符串s进行遍历,并将字符插入到对应的string中,最后将所有string相加,即可得到所要
的结果字符串。
class Solution {
public:
string convert(string s,int nRows)
{
if(s=="")
return s;
int len=s.size();
if(nRows==1)
return s;
else if(nRows==2)
{
string res="";
for(int i=0;
i
推荐阅读
- 数据结构与算法|【算法】力扣第 266场周赛
- leetcode|今天开始记录自己的力扣之路
- Python|Python 每日一练 二分查找 搜索旋转排序数组 详解
- 【LeetCode】28.实现strstr() (KMP超详细讲解,sunday解法等五种方法,java实现)
- LeetCode-35-搜索插入位置-C语言
- leetcode python28.实现strStr()35. 搜索插入位置
- Leetcode Permutation I & II
- python|leetcode Longest Substring with At Most Two Distinct Characters 滑动窗口法
- LeetCode 28 Implement strStr() (C,C++,Java,Python)
- Python|Python Leetcode(665.非递减数列)