leetcode zigzag conversion
来源:互联网 发布:22级战舰升级数据 编辑:程序博客网 时间:2024/06/07 13:28
https://leetcode.com/problems/zigzag-conversion/
思路1
其实这里只需要找出一般公式就行,没什么技巧。当i是1到n-2行时,第i行第一个在斜线上的元素在s中的index是 2 numRows - 2, 所以与第i行第一个元素 i (以及后面增加2 numRows - 2后的j),相差 2 numRows - 2 - 2 i个元素。
my code:
class Solution(object): def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ if len(s) == 1 or numRows == 1: return s res = [] for i in xrange(numRows): j = i while j < len(s): res.append(s[j]) if i >0 and i < numRows - 1: tmp = j + 2*numRows - 2 - 2*i if tmp < len(s): res.append(s[tmp]) j += 2*numRows - 2 return "".join(res)
思路2
http://www.cnblogs.com/zuoyuan/p/3777745.html
其中index是tmp中哪一行的index,这个index的变化是0,1,2,..., nRow - 1, nRow(这个值已经是在斜线上的元素) ->转换成nRow - 2, nRow - 3, ..., 2, 1, 0, -1->转化成1,2,...
这里step就是1和-1,用来调整index的运动方向的
class Solution: # @return a string def convert(self, s, nRows): if nRows==1: return s tmp=['' for i in range(nRows)] index=-1; step=1 for i in range(len(s)): index+=step if index==nRows: index-=2; step=-1 elif index==-1: index=1; step=1 tmp[index]+=s[i] return ''.join(tmp)
思路3
直接把zigzag放到2Dmatrix里面,然后输出就行了。
http://yucoding.blogspot.hk/2013/02/leetcode-question-125-zigzag-conversion.html
0 0
- LeetCode: ZigZag Conversion
- LeetCode : ZigZag Conversion
- leetcode 13:zigzag conversion
- [LeetCode] Zigzag Conversion
- LeetCode 6 - ZigZag Conversion
- Leetcode : ZigZag Conversion
- 【leetcode】Zigzag Conversion
- [LeetCode]ZigZag Conversion
- leetcode ZigZag Conversion
- LeetCode-ZigZag Conversion
- LeetCode ZigZag Conversion
- LeetCode 6: ZigZag Conversion
- leetcode-006:ZigZag Conversion
- Leetcode: ZigZag Conversion
- [LeetCode]ZigZag Conversion
- [LeetCode] ZigZag Conversion
- [LeetCode]ZigZag Conversion
- leetcode: ZigZag Conversion
- 实现一段字符串中部分内容字体颜色大小变化
- 对触发器的认识
- fragment之生命周期
- LINUX 系统中SD卡分区
- 02 ehcache.xm讲解
- leetcode zigzag conversion
- Microsoft HoloLens
- 欢迎使用CSDN-markdown编辑器
- hibernate的Configuration类
- TCP与UDP的区别
- torch学习(六) rnn package
- 黑马程序员_static关键字和构造代码块
- 黑马程序员--File类
- LeetCode 之 Minimum Depth of Binary Tree