ZigZag Conversion
题目:
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
中间横线是我加上去的,否则makedown语言看不出来锯齿形状
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”.
题意:
给出一个字符串,然后把字符串转换称N字形状连接,如下图形状,然后一行一行输出字母即可。
输出:1,7,13,2,6,8,12,14,3,5,9,11,15,17,4,10,16
思路:
把上图想象成下图
首先按照块来区分,图中分了3块,题目中给定参数numRows,那么每块的大小为numRows+numRows-2 = numRows*2-2,先分好块后,我们会发现,每块的第二竖列相对于第一竖列是逆序的,那么我们就分块后在把它逆序,逆序后我是让它居中对齐且补充空格,这样就成为了一个二维矩阵如下图
然后按行输出即可,遇到空格不输出。注意下最后一块因为会缺少,我是补充了空格。
题目要求是返回一个字符串。
代码:
#!usr/bin/env python
#coding:UTF-8
List = []
NewList = []
def func(str, numRows):
size = numRows*2-2
if size == 0:
return size
if len(str)%size == 0:
g = len(str)/size
else:
g = len(str)/size+1
str += (size-len(str)%size)*' '
for i in range(g):
List.append(str[size*i:size*i+size])
for s in List:
print s
l1 = list(s[:numRows])
l2 = list(s[size:size/2:-1].center(numRows))
NewList.append(l1)
NewList.append(l2)
s = ''
print NewList
for i in range(numRows):
for j in NewList:
if j[i] != ' ':
s += j[i]
print s
if __name__ == '__main__':
func('PAYPALISHIRING', 3)
运行结果:
要注意的一些小细节