33.leetcode6_zigzag_conversion

1.题目描述

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"

按矩阵格式,“Z”型转变字符串

2.题目分析

可以按照给定的列数分出三个子字符串,放在一个列表中。在第一个字符串时规定步数为1,下一个字符连接到第二个字符串上;第numRows-1个字符串时规定步数为-1,下一个字符连接到上一个字符串上。

3.解题思路

 1 class Solution(object):
 2     def convert(self, s, numRows):
 3         """
 4         :type s: str
 5         :type numRows: int
 6         :rtype: str
 7         """
 8         list1=[]
 9         l=len(s)
10         if numRows==1: #numRows为1,输出原字符串
11             return s
12         for i in range(0,numRows): #列表中添加numRows个空字符串
13             list1.append("")
14         row=0
15         step=1 #初始步数为1
16         for j in s:
17             if row==0:
18                 step=1
19             if row==numRows-1: #遇到列表中最后一个字符串,向回走
20                 step=-1
21             list1[row]+=j
22             row+=step     
23         list2="".join(list1)  #列表转字符串
24         return list2

 

posted @ 2018-02-23 23:32  vlice  阅读(69)  评论(0编辑  收藏  举报