您的位置:首页 > 其它

leetcode笔记--ZigZag Conversion

2016-02-23 15:35 441 查看
题目:难度(Easy)

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".

Tags:String

分析:将字符串按行排列成“z”字形,然后按规则回收时组成一个新的串返回。

意思如图(图中数字为原字符串的索引):

当numRows = 3时, 当numRows = 4时, 当numRows = 5时,







从上图中我们可以总结出来新的串的索引值与原串的索引值的对应关系。

对于每一行i来说(除去对角线上的元素),每2个元素之间的差值delta=2*numRows-2,如numRows = 4时,从0、6、12、1、7、13、2、8等等,可知delta = 2*numRows-2 = 6; 而对于中间行来说(不含第一行和末行),每2个元素之间都会增加1个元素,且该元素的索引值与同行中他的前一个元素的索引值的差值delta' = delta - 2*i(i为行号),所以如果求出他的前一个元素的索引值,我们只需要接下来在钱一个索引值的基础上加上一个新的delta' = delta
- 2 * i

代码实现:

class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if s == "" or numRows <= 1:
return s
resultStr = ""
delta = 2*numRows - 2
#对于所有的行(除去对角线上的元素不看),之间的delta=2*numRows-2,
for i in range(numRows):
for j in range(0, len(s), delta):
if i + j < len(s):
resultStr += s[i + j]
#当处理中间行时(除开第一行和末行),每一个delta间隔之间一会再增加一个元素,且形成的新delta'=delta - 2 * i
#即对角线上的元素,他总是同行中他前一个元素的索引的基础上再加上一个新的delta'
#由于前一个的索引是i + j ,所以对角线上的索引总是i + j + delta' = delta + j - i
if i > 0 and i < numRows-1 and delta -i + j < len(s):
resultStr += s[delta -i + j]
return resultStr


还有一种比较直观的方法是用一个字符串数组来存储每一行,再把每一行串接起来形成整个串。执行过程:把原串的每个字符依次分发到字符串数组里

代码实现:

class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if s == "" or numRows <= 1:
return s
#初始化一个字符串数组
strTest = ["" for i in range(numRows)]
#irow控制行号,即字符串数组strTest的第几个字符串
irow = 0
#direction控制在分发原串的字符时,是正着往strtest里发,还是倒着发
direction = 1
for i in range(len(s)):
if direction > 0:
strTest[irow] += s[i]
irow += 1
else:
irow -= 1
strTest[irow] += s[i]

if irow == 0:
direction = 1
irow += 1
if irow == numRows:
direction = -1
irow -= 1
return "".join(strTest)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: