LeetCode-6
Zigzag Conversion : The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows
note : like this: (you may want to display this pattern in a fixed font for better legibility)
Answer
:::python
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows==1:
return s
answer = ''
interval = numRows + (numRows-2)
ls = [[''] for _ in range(numRows)]
for i, l in enumerate(s):
inter = i%interval
if inter < numRows:
ls[inter]+=l
else:
ls[interval-(inter)]+=l
return ''.join(sum(ls,[]))
Result : 97ms Memory: 14.2mb
Zigzag Conversion
Zigzag Conversion์ ๋ฌธ์์ด์ ์ง๊ทธ์ฌ๊ทธ ํํ๋ก ๋ณํํ๋ ์๊ณ ๋ฆฌ์ฆ์ ๋๋ค.
๋ฌธ์ ์ค๋ช
์ฃผ์ด์ง ๋ฌธ์์ด s
์ ์ ์ numRows
๊ฐ ์ฃผ์ด์ง๋ฉด, s
๋ฅผ ์ง๊ทธ์ฌ๊ทธ ํํ๋ก ๋ณํํฉ๋๋ค.
์๋ฅผ ๋ค์ด, ๋ค์๊ณผ ๊ฐ์ ๋ฌธ์์ด๊ณผ numRows
๊ฐ ์ฃผ์ด์ก๋ค๊ณ ๊ฐ์ ํด๋ด
์๋ค.
s = "PAYPALISHIRING"
numRows = 3
๊ทธ๋ฌ๋ฉด ๋ฌธ์์ด s
๋ ๋ค์๊ณผ ๊ฐ์ด ๋ณํ๋ฉ๋๋ค.
P A H N
A P L S I I G
Y I R
์ฆ, numRows
๊ฐ์ ํ์ผ๋ก ๊ตฌ์ฑ๋ ํ์ ๋ฌธ์์ด s
๋ฅผ ์ ์ ํ๊ฒ ๋ฐฐ์นํ์ฌ ์์ ๊ฐ์ ๋ชจ์์ ๋ง๋ญ๋๋ค.
ํด๊ฒฐ ๋ฐฉ๋ฒ
Zigzag Conversion ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๊ธฐ ์ํด์๋ ๋ค์๊ณผ ๊ฐ์ ์๊ณ ๋ฆฌ์ฆ์ ์ฌ์ฉํ ์ ์์ต๋๋ค.
numRows
๊ฐ์ ๋น ๋ฌธ์์ด ์์ฑ๋ฌธ์์ด
s
๋ฅผ ์ฒ์๋ถํฐ ๋๊น์ง ์ํํ๋ฉด์ ๋ค์๊ณผ ๊ฐ์ ๊ณผ์ ์ ๋ฐ๋ณตํฉ๋๋ค.ํ์ฌ ๋ฌธ์๋ฅผ
row
๋ฒ์งธ ํ์ ์ถ๊ฐํฉ๋๋ค.row
๊ฐ์ด 0์ด๊ฑฐ๋numRows - 1
์ด๋ฉด ๋ฐฉํฅ์ ์ ํํฉ๋๋ค.ํ์ฌ ๋ฐฉํฅ์ ๋ฐ๋ผ
row
๊ฐ์ ์ฆ๊ฐํ๊ฑฐ๋ ๊ฐ์ํฉ๋๋ค.
์์ฑ๋
numRows
๊ฐ์ ๋ฌธ์์ด์ ์์๋๋ก ์ด์ด๋ถ์ธ ๊ฒฐ๊ณผ๋ฅผ ๋ฐํํฉ๋๋ค.
์๋ฅผ ๋ค์ด, ์์ ๋์จ ์์ ๋ฅผ ์์ ์๊ณ ๋ฆฌ์ฆ์ผ๋ก ํด๊ฒฐํด๋ณด๋ฉด ๋ค์๊ณผ ๊ฐ์ต๋๋ค.
s = "PAYPALISHIRING"
numRows = 3
์ด๊ธฐ ์ํ:
["", "", ""]
s[0] = "P" ์ถ๊ฐ:
["P", "", ""]
s[1] = "A" ์ถ๊ฐ:
["P", "A", ""]
s[2] = "Y" ์ถ๊ฐ:
["P", "A", "Y"]
๋ฐฉํฅ ์ ํ:
["P", "A", "Y"]
["", "L", ""]
s[3] = "P" ์ถ๊ฐ:
["P", "A", "Y"]
["", "L", "P"]
s[4] = "A" ์ถ๊ฐ:
["P", "A", "Y"]
["", "L", "PA"]
s[5] = "L" ์ถ๊ฐ:
["P", "A", "Y"]
["", "L", "PAL"]
s[6] = "I" ์ถ๊ฐ:
["P", "A", "Y"]
["I", "L", "PAL"]
s[7] = "S" ์ถ๊ฐ:
["P", "A", "Y"]
["I", "LS", "PAL"]
s[8] = "H" ์ถ๊ฐ:
["P", "A", "Y"]
["I", "LSH", "PAL"]
s[9] = "I" ์ถ๊ฐ:
["P", "A", "Y"]
["IH", "LSH", "PAL"]
s[10] = "R" ์ถ๊ฐ:
["P", "A", "Y"]
["IH", "LSHR", "PAL"]
์ต์ข
๊ฒฐ๊ณผ: "PAHNAPLSIIGYIR"
'๐ข One step' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[leetcode-10] Regular Expression Matching (0) | 2023.04.20 |
---|---|
[leetcode-8] String to Integer (atoi) (0) | 2023.04.19 |
[leetcode-7] Reverse Integer (0) | 2023.04.16 |
[leetcode-9] Palindrome Number (0) | 2023.04.15 |
[leetcode-4] Median of Two Sorted Arrays (0) | 2023.04.14 |