题目:
The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this:
我的思路:
把s拆成给定的行数,依次把s的每个元素加至正确的行中
Runtime: 68 ms(36.82%),Memory Usage: 14.6 MB(24.24%),复杂度:O(len(s))
我的解答:
class Solution:
def convert(self, s: str, numRows: int) -> str:
# given a list of
ans = [s[0]]
for x in range(1,numRows):
ans.append('')
if len(s) == 1 or numRows == 1 or numRows > len(s):
return s
for i in range((len(s)-1)//(numRows-1)):
for j in range(numRows-1):
if i%2 == 0:
ans[j+1] += (s[(numRows-1)*i+j+1])
else:
ans[numRows-2-j] += (s[(numRows-1)*i+j+1])
for t in range((len(s)-1)%(numRows-1)):
if ((len(s)-1)//(numRows-1))%2 == 0:
ans[t+1] += (s[((len(s)-1)//(numRows-1))*(numRows-1)+1+t])
else:
ans[numRows-2-t] += (s[((len(s)-1)//(numRows-1))*(numRows-1)+1+t])
str_ans = ''
for m in ans:
str_ans += m
return str_ans
答案:
除了我的答案,还有一种方法,但是算法和复杂度没有区别,即直接每次把每一行的元素一次算完,例如第二行包含的元素有:1,1+numRows,1+numRows+2X1, 1+numRows+2X1+numRows …