Description:
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)
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 s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
Step 1 : 標記 每個字母出現的位置
class Solution:
def convert(self, s: str, numRows: int) -> str:
slen =len(s)
pos = []
row = 1
flag = 0
for i in range(slen):
if row==numRows:
#print("z")
#row-=1
#print("r:"+str(row))
pos.append(row)
row = row -1
flag = 1 # go up
elif row==1:
pos.append(row)
row = row +1
flag = 0
else:
pos.append(row)
if flag == 0:
row = row +1
else:
row = row -1
print(pos)
Step 2-1 : 顯示出來
class Solution:
def convert(self, s: str, numRows: int) -> str:
slen =len(s)
pos = []
row = 1
flag = 0
for i in range(slen):
if row==numRows:
#print("z")
#row-=1
#print("r:"+str(row))
pos.append(row)
row = row -1
flag = 1 # go up
elif row==1:
pos.append(row)
row = row +1
flag = 0
else:
pos.append(row)
if flag == 0:
row = row +1
else:
row = row -1
print(pos)
ans =""
for i in range(numRows): # sum of round
for j in range(len(s)):
if pos[j] == (i+1):
ans+=s[j]
print(ans)
return ans
Step 2-2 : 沒有這步 會過不了 numRows 為1的情況
先判斷 numRows是否是 1 ,是的話,直接回傳 input 字串
class Solution:
def convert(self, s: str, numRows: int) -> str:
slen =len(s)
pos = []
row = 1
flag = 0
if numRows==1:
return s
for i in range(slen):
if row==numRows:
#print("z")
#row-=1
#print("r:"+str(row))
pos.append(row)
row = row -1
flag = 1 # go up
elif row==1:
pos.append(row)
row = row +1
flag = 0
else:
pos.append(row)
if flag == 0:
row = row +1
else:
row = row -1
print(pos)
ans =""
for i in range(numRows): # sum of round
for j in range(len(s)):
if pos[j] == (i+1):
ans+=s[j]
print(ans)
return ans
Result