题目:
将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 “PAYPALISHIRING” 行数为 3 时,排列如下:
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如"PAHNAPLSIIGYIR"。
示例:
输入:s = “PAYPALISHIRING”, numRows = 4
输出:“PINALSIGYAHRPI”
思路:
遍历字符串,然后将字符放到相应的位置上,可以看到摆放位置依次是第0行到第n-1行,然后从n-1行到第0行,直到遍历完,可以生成n个字符串,来保存这些行,最后再将这些行连接起来,组成一个字符串返回。
具体过程是:
设置行数个空字符串,dir表示放置方向,true就是从上往下放,放好一个以后当前行数加1,false就是从下往上放,放好一个后当前行数减1,当到达第一行或者最后一行后改变方向,最后将几个字符串连接起来,返回。
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
row = ['' for _ in range(numRows)]
cur_row = 0
dir = True
if numRows == 1:
return s
for i,char in enumerate(s):
row[cur_row] += char
if dir:
cur_row += 1
else:
cur_row -= 1
if cur_row == 0 and not dir:
dir = True
if cur_row == numRows-1 and dir:
dir = False
res = ''
for c in row:
res += c
return res