题目链接
https://leetcode.com/problems/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
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”.
题目翻译
zigzag字符串转换,具体的规则见题目原文,太长不翻译了。。。
要写的函数接收两个参数,要转换的字符串text和zigzag的行数nRows,返回转换后的字符串。
思路方法
思路一
模拟书写zigzag字符串的过程。定义一个有numRows个元素的数组,每个元素初始是空字符串,代表numRows个行字符串的初始情况;然后扫描输入字符串s,依次将每个字符添加到相应行字符串的末尾;最后将所有行字符串拼接即得结果。
注意,代码中用了取模操作来判断:是否到了需要换一个方向书写zigzag字符的时候。
代码
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows <= 1 or numRows >= len(s):
return s
arr = [''] * numRows
line, step = 0, -1
for c in s:
arr[line] += c
if line % (numRows-1) == 0:
step = - step
line += step
return ''.join(arr)
思路二
如果稍微考虑的数学一点,那么s中的第i个字符(下标从第0个开始),如果按照zigzag书写方式会出现在的行数为(行数为0到numRows-1行):
i % (2 * numRows - 2), if i % (2 * numRows - 2) < numRows
2 * numRows - 2 - (i % (2 * numRows - 2)), if i % (2 * numRows - 2) >= numRows
有了这个结果,对于任意一个位置的字符我们都知道它应该在第几行。下面的代码仍然是顺序扫描原字符串s,当然也可以有别的办法。
代码
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows <= 1 or numRows >= len(s):
return s
arr = [''] * numRows
for i in xrange(len(s)):
tmp = i % (numRows + numRows - 2)
if tmp < numRows:
arr[tmp] += s[i]
else:
arr[numRows + numRows - 2 - tmp] += s[i]
return ''.join(arr)
PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.youkuaiyun.com/coder_orz/article/details/52039689