方法一:找规律
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if len(s) < numRows:
numRows = len(s)
midRows = numRows - 2
length = len(s)
if length == 1:
return s
if numRows == 1:
return s
news = ""
start = 0
end = numRows - 1
plus = midRows * 2 + 1 * 2
while start < length:
news += s[start]
start += plus
midnums = 0
for i in range(numRows - 2):
midnums = i + 1
news += s[midnums]
plusZ1 = (midRows - (i + 1)) * 2 + 1 * 2
plusZ2 = plus - plusZ1
while midnums + plusZ1 < length:
midnums += plusZ1
news += s[midnums]
if midnums + plusZ2 < length:
midnums += plusZ2
news += s[midnums]
else:
break
while end < length:
news += s[end]
end += plus
return news
方法一:压缩矩阵
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
length = len(s)
if numRows == 1 or length < numRows:
return s
mat = [[] for _ in range(numRows)]
x, t = 0, 2 * numRows - 2
for i, v in enumerate(s):
mat[x].append(v)
x += 1 if i % t < numRows - 1 else -1
s1 = ""
for _ in range(numRows):
s1 += "".join(mat[_])
return s1
总结
1、方法一是纯粹找规律的,画出矩阵能够观察得出,n行的矩阵可分为两类,第一行与最后一行一类,中间行一类;通过找规律依次输出每一行即可。
2、方法二的压缩矩阵很巧妙,通过观察得出,每一个字符都可以视为添加到了所在矩阵行的正右边第一个。这一点方便后面我们的遍历,同时引出了巧妙的这里:
x, t = 0, 2 * numRows - 2
for i, v in enumerate(s):
mat[x].append(v)
x += 1 if i % t < numRows - 1 else -1
尤其是这里的上下波动添加字符,这里的逻辑循环值得认真学习。
同时循环外使用x,循环内使用enumerate函数的i,v,也值得学习并在今后使用。
3、字典与哈希表的关系:在python中,哈希表是实现字典的其中一种方式,除了哈希表,实现字典的另一种常见方式是红黑树。
4、列表转化为字符串:
''.join(list)
5、replace()方法,去除字符串全部空格:
a = " a b c "
>>> a.replace(" ", "")
# 输出'abc'
6、join()方法+split()方法,去除字符串全部空格:
.split()将字符串分割后,填入列表中;
.join()再将列表中的值合在一起。
a = " a b c "
"".join(a.split())
# 输出'abc'
7、字符串指定位置插入字符:
str_list.insert(5, a)