728x90

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 ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

  1. numRows๊ฐœ์˜ ๋นˆ ๋ฌธ์ž์—ด ์ƒ์„ฑ

  2. ๋ฌธ์ž์—ด s๋ฅผ ์ฒ˜์Œ๋ถ€ํ„ฐ ๋๊นŒ์ง€ ์ˆœํšŒํ•˜๋ฉด์„œ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๊ณผ์ •์„ ๋ฐ˜๋ณตํ•ฉ๋‹ˆ๋‹ค.

    1. ํ˜„์žฌ ๋ฌธ์ž๋ฅผ row๋ฒˆ์งธ ํ–‰์— ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค.

    2. row๊ฐ’์ด 0์ด๊ฑฐ๋‚˜ numRows - 1์ด๋ฉด ๋ฐฉํ–ฅ์„ ์ „ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

    3. ํ˜„์žฌ ๋ฐฉํ–ฅ์— ๋”ฐ๋ผ row๊ฐ’์„ ์ฆ๊ฐ€ํ•˜๊ฑฐ๋‚˜ ๊ฐ์†Œํ•ฉ๋‹ˆ๋‹ค.

  3. ์ƒ์„ฑ๋œ 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
๋‹คํ–ˆ๋‹ค