LeetCode-006 ZigZag Conversion
来源:互联网 发布:尼康失真控制数据 编辑:程序博客网 时间:2024/06/06 05:26
Description
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 text, int nRows);
convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.
Analyse
这其实是一道字符串题目,但这道题有点毛病,乍一看不懂它的要求是什么,我们根据标题可推理出,它是想让我们把字符串按照类似拉链一样排列,也就是“Z”字型排列。举个例子:
画了个图,不好看请见谅(捂脸)
你会发现这样一个规律(n>1),上面的数字为字符标号,然后我们就可以直接根据这个规律来写代码啦。
规律为:当字符的下标不超过字符串长度时,每两个竖列的对应横排的数相差(2n-2),然后中间的数按照公差为2这样的速率向下变动,直到这个变化为0,那么就完成了。也就是,第一列的公差为(2n-2),第二列的公差为(2n-4)和2交替进行,然后按照这个规律向下变化。
最后一行跟第一行需要拿出来特殊处理,其它的可以一并处理。
对于n=1的情况,输出字符串为原字符串,需要特殊处理。
算法结束。
Code
class Solution {public: string convert(string s, int numRows) { int len=s.length(); string ans=""; if (numRows==1) return s; for (int i=0;i<numRows;i++) { int p=i; while (p<len) { //最后一行的判断 if (i!=numRows-1) { ans=ans+s[p]; p=p+2*(numRows-i-1); } if (p>=len) break; //第一行的判断 if (i!=0) { ans=ans+s[p]; p=p+2*i; } } } return ans; }};
- leetcode-006:ZigZag Conversion
- LeetCode 006 ZigZag Conversion
- LeetCode 006 ZigZag Conversion
- [LeetCode]-006-ZigZag Conversion
- 006 ZigZag Conversion [Leetcode]
- [LeetCode]006-ZigZag Conversion
- LeetCode 006 ZigZag Conversion
- leetcode ZigZag Conversion 006
- LeetCode 006 ZigZag Conversion
- leetcode-006 ZigZag Conversion
- leetcode 006 ZigZag Conversion
- LeetCode-006 ZigZag Conversion
- [LeetCode OJ][006]ZigZag Conversion
- leetcode 006 —— ZigZag Conversion
- leetcode之路006 ZigZag Conversion
- LeetCode: ZigZag Conversion
- LeetCode : ZigZag Conversion
- leetcode 13:zigzag conversion
- Spring Cloud (14) | 微服务不能从git/github/gitlab中获取数据库信息 can't load properties from git/github/gitlab
- Python基础篇之迭代
- JAVA程序性能调优(一)
- Lintcode:字符串查找
- SQL中关于EXISTS谓词的理解
- LeetCode-006 ZigZag Conversion
- 如何自学python
- 总结这7年前端UI框架的总结与发展
- TensorFlow中tf.train.exponential_decay的用法
- LXC:Linux 容器工具
- 未来工业智能峰会|看中船、中车的数据智能化之路
- flume中的TaildirSource(1)
- mysql生成一条A表数据的同时得到这条数据的自增ID
- React前端入门学习