码迷,mamicode.com
首页 > 其他好文 > 详细

33.leetcode6_zigzag_conversion

时间:2018-02-24 00:56:49      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:his   字符串   pattern   join   self   ==   第一个   sel   lis   

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

 

33.leetcode6_zigzag_conversion

标签:his   字符串   pattern   join   self   ==   第一个   sel   lis   

原文地址:https://www.cnblogs.com/19991201xiao/p/8463853.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!