本人算法萌新,为秋招找工作开始磨炼算法,算法题均用python实现,如果我有哪些地方做的有问题的,还请大家不吝赐教.
1.题干
将一个给定字符串
s
根据给定的行数numRows
,以从上往下、从左到右进行 Z 字形排列。比如输入字符串为
"PAYPALISHIRING"
行数为3
时,排列如下:P A H N A P L S I I G Y I R之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:
"PAHNAPLSIIGYIR"
。请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);示例 1:
输入:s = "PAYPALISHIRING", numRows = 3 输出:"PAHNAPLSIIGYIR"示例 2:
输入:s = "PAYPALISHIRING", numRows = 4 输出:"PINALSIGYAHRPI" 解释: P I N A L S I G Y A H R P I示例 3:
输入:s = "A", numRows = 1 输出:"A"提示:
1 <= s.length <= 1000
s
由英文字母(小写和大写)、','
和'.'
组成1 <= numRows <= 1000
2.思考
粗看题目,感觉是寻找字符串index和numRows之间的关系,本质上是用找规律做的
3.代码
class Solution:
def convert(self, s: str, numRows: int) -> str:
n = len(s)
if n <= numRows or numRows == 1:
return s
ans = ''
first_length = 2 * (numRows - 1)
other_length = first_length
for i in range(0, n, first_length):
ans += s[i]
print(ans)
for i in range(1, numRows - 1):
other_length -= 2
ans += s[i]
j = i + other_length
is_ok = False
while numRows <= j < n:
ans += s[j]
if not is_ok:
length = first_length - other_length
is_ok = True
else:
length = other_length
is_ok = False
j += length
print(ans)
for i in range(numRows - 1, n, first_length):
ans += s[i]
return ans
4.总结
找规律找规律Oh Yeah