[ LeetCode ]- ZigZag Conversion 解答
来源:互联网 发布:java post 提交文件 编辑:程序博客网 时间:2024/05/16 15:24
原题目:
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 NA P L S I I GY I RAnd 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"
.
题目的意思是说将字符 一个个 按照 纵向 从上到下再从下到上,如此反复排列。然后让我们按行来拼接它们。
Demo1 (3行)
1 52463 7Demo2 (4行)
1 72683594 10Demo3 (5行)
1 92810371146125 13 我们看完上面3个例子,不难发现 奇数列的间隔分别是:4 , 6 , 8。而我们三个Demo的行数是:3,4,5. 那么不然得出。 奇数列间隔 = 2*行数 - 2;
那么看偶数列间隔,偶数列有个特点是不包含在 首行和末尾行的,所以在推算的时候要排除掉。
拿Demo3 为例: 第二列比第一列的差依次为:6,4,2.
那么不难看出:偶数列间隔 = 奇数列间隔 - 行数*2
OK,那么代码就好写了:
class Solution(object): def convert(self, s, numRows): if len(s)>0 and numRows >1: row = 0 offset = 2*numRows -2 result = '' while row < numRows: col = row while col < len(s): result += s[col] if row!=0 and row != numRows-1: index =col + offset - 2* row if index < len(s): result += s[index] col += offset row +=1 return result else: return s
0 0
- [ LeetCode ]- ZigZag Conversion 解答
- leetcode习题解答:6. ZigZag Conversion
- 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
- mac osx
- Maven + Spring MVC+Mybatis + MySQL +AngularJS + Bootstrap 实现简单微博应用(三)前后台交互
- python 单下划线/双下划线使用总结
- 屏蔽淘宝二维码登录
- Ajax工作原理/JQuery中AJAX调用
- [ LeetCode ]- ZigZag Conversion 解答
- 关于struts2和ajax的关系
- #Qt on android#使用Qt 获取GPS信号
- Java并发编程(19):并发新特性—Executor框架与线程池(含代码)
- 自制图像(视觉)处理库
- pip 常用命令
- 安卓开发过程中Intent的使用
- VM虚拟机上不了网
- 调整数组顺序使奇数位于偶数前面