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 |
str = 'abcde' |
list->str:
1 |
list = ['a','b','c','d','e'] |
我对此题的解法为模拟,设计一个flag变量,为-1时方向向下,为+1时方向向上,将string填入二维的list中:
1 |
class : |
近期评论