leetcode(6) 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".

解法:

python 创建二维列表,将需要的参数写入 cols 和 rows 即可

1
list_2d = [[0 for col in range(cols)] for row in range(rows)]

此外,此题中还需要注意的是python中list与str的互相转换:
str->list:

1
2
str = 'abcde'
list = list(str)

list->str:

1
2
list = ['a','b','c','d','e']
str_convert = ''.join(list)

我对此题的解法为模拟,设计一个flag变量,为-1时方向向下,为+1时方向向上,将string填入二维的list中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class :
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if(numRows == 1 or numRows >= len(s)):
return s;
L = [[] for row in range(numRows)];
r = 0;i = 0;flag = -1;
while(i< len(s)):
if(flag == -1):
L[r].append(s[i]);
r+=1;
if(r == numRows):
flag = 1;
r = numRows - 2;
else:
L[r].append(s[i]);
r-=1;
if(r == -1):
flag = -1;
r = 1;
i+=1;
result = ""
for i in range(numRows):
r = ''.join(L[i]);
result += r;
return result