[leetcode]6. ZigZag Conversion
2016-03-15 21:36
225 查看
The string “
And then read line by line: “
Write the code that will take a string and make this conversion given a number of rows:
convert(“
https://leetcode.com/problems/zigzag-conversion/
观察坐标变化 第一行和最后一行,相邻行的坐标差都是
既然用python做,那么应该很少代码才对,利用
换个形式看上面的”压缩”后的结果
result[1]=
result[2]=
result[3]=
然后
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“.
https://leetcode.com/problems/zigzag-conversion/
n=2时,字符串坐标变成zigzag的走法就是: 0 2 4 6 1 3 5 7 n=3时的走法是: 0 4 8 1 3 5 7 9 2 6 10 n=4时的走法是: 0 6 12 1 5 7 11 13 2 4 8 10 14 3 9 15
观察坐标变化 第一行和最后一行,相邻行的坐标差都是
2n-2,其他行坐标
j+(2n-2)-2i,以行遍历
class Solution(object): def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ if (len(s)==0 or numRows <=0): return '' if numRows == 1: return s ret = [] size = 2*numRows-2 for i in range(0,numRows): for j in range(i,len(s),size): ret.append(s[j]) if (i!=0 and i!=numRows-1): temp = j + size -2*i if temp<len(s): ret.append(s[temp]) return ''.join(ret)
既然用python做,那么应该很少代码才对,利用
list[-1]
list[-2]的特性
ABCDEFG A E BD C F # n=3 将空格出压缩到下面形式 AE BDG CF
换个形式看上面的”压缩”后的结果
result[1]=
AE
result[2]=
BDG
result[3]=
CF
然后
AE+
BDG+
CF,这样就得到最后结果了。~
class Solution(object): def convert(self, s, numRows): result = [""] * (numRows + 1) #保存每一行的结果 level, order = 1, 1 # order指示是否逆序 for i in s: result[level*order] += i #对应行加入字母 level += 1 if level >= numRows: # 判断是否应该逆序 level, order = 1, order * (-1) return "".join(result)
相关文章推荐
- 05.文件系统
- 用Python语言写Hadoop MapReduce程序Writing an Hadoop MapReduce Program in Python
- 面向对象编程(四)继承,概念及super关键字,final关键字,Object类常见方法
- 第五十三天
- 关于阿里云服务器CentOS7的防火墙问题
- oracle 学习笔记 number
- C++中的单例模式(singleton)
- linux下安装tomcat
- 分数线划定
- windows 7下,给android ndk编译libcurl
- Android开发Style的使用,控件共同属性的抽取
- java SE基础(URL访问网络资源)
- 深入学习JVM堆与JVM栈(精华)
- Cocos2dx -- 入门之c++ 调用lua
- 03.deamon进程
- 04.LVM
- matconvnet编译
- HTTP 单线程 模拟迅雷下载
- 校园网&openwrt记(十五)luci module
- leetcode 49. Group Anagrams