반응형
Zigzag Conversion
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)
P A H N
A P L S I I G
Y I R
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:
P I N
A L S I G
Y A H R
P I
Example 3:
Input: s = "A", numRows = 1
Output: "A"
Constraints:
1 <= s.length <= 1000sconsists of English letters (lower-case and upper-case),','and'.'.1 <= numRows <= 1000
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1 or len(s) == 1 :
return s
idx = 0
d = 1
word_stack = [[] for _ in range(numRows)]
for j in range(len(s)) :
if idx == 0 :
d = 1
elif idx == numRows - 1 :
d = -1
word_stack[idx].append(s[j])
idx += d
res = []
for word in word_stack :
res += word
return "".join(res)
처음에는 좀 헤맸다.
- 지그재그 형태를 어떻게 구현할까.
이 부분은 참고를 하였다. idx가 처음이면 +1로, numRows이면 -1로 바꿔서 계속해서 더해준다. 코드를 보면 비교적 쉽게 해결할 수 있다.
처음 가지치기를 안해서 오답을 제출했다.
반응형
'알고리즘 스터디' 카테고리의 다른 글
| [Leetcode/파이썬] 637. Average of Levels in Binary Tree (0) | 2026.01.29 |
|---|---|
| [Leetcode/파이썬] 23. Merge K Sorted Lists (0) | 2026.01.19 |
| [Leetcode/파이썬] 151. Reverse Words in a String (0) | 2026.01.18 |
| [Leetcode/파이썬] 148. Sort List (0) | 2026.01.17 |
| [Leetcode/파이썬] 92. Reverse Linked List II (0) | 2026.01.17 |