https://leetcode.com/problems/count-and-say
Count and Say - LeetCode
Can you solve this real interview question? Count and Say - The count-and-say sequence is a sequence of digit strings defined by the recursive formula: * countAndSay(1) = "1" * countAndSay(n) is the run-length encoding of countAndSay(n - 1). Run-length enc
leetcode.com
이 문제는 한국에서는 베르나르 베르베르의 소설 '개미'에 등장하여 흔히 **"개미 수열"**이라고도 불리는 Count-and-Say (읽고 말하기) 수열 문제입니다.
반복적인 방법(Iterative)을 사용한 논리와 파이썬 풀이를 단계별로 설명해 드리겠습니다.
이 문제의 핵심은 이전 단계의 문자열을 소리 내어 읽는 것입니다. 이를 **런 렝스 부호화(Run-Length Encoding)**라고도 합니다.
문자열을 왼쪽에서 오른쪽으로 훑으며, 연속된 동일한 숫자를 그룹으로 묶습니다. 각 그룹에 대해 다음 두 가지 정보를 결합합니다:
예시 (일 때):
재귀(Recursion)를 사용하지 않고 반복문으로 처리하면 스택 오버플로우를 방지하고 메모리를 더 효율적으로 사용할 수 있습니다.
class Solution:
def countAndSay(self, n: int) -> str:
# 기본 케이스 처리
if n == 1:
return "1"
# 첫 번째 수열 시작
current_s = "1"
# 2부터 n까지 반복하며 다음 수열 생성
for _ in range(2, n + 1):
next_s = []
i = 0
length = len(current_s)
while i < length:
count = 1
# 현재 위치(i)의 문자와 다음 문자가 같으면 count 증가
while i + 1 < length and current_s[i] == current_s[i+1]:
i += 1
count += 1
# '개수'와 '숫자'를 리스트에 추가
next_s.append(str(count))
next_s.append(current_s[i])
# 다음 새로운 숫자로 이동
i += 1
# 리스트를 문자열로 합쳐서 current_s 갱신
current_s = "".join(next_s)
return current_s
| 코딩테스트 연습 - 기초트레이닝(LV 0) (0) | 2026.01.03 |
|---|---|
| algorithm weekly ~ 2022.02.06 (0) | 2022.02.04 |
| Weekly Contest 277 (0) | 2022.01.23 |
| 2033. Minimum Operations to Make a Uni-Value Grid (0) | 2021.10.10 |
| 2032. Two Out of Three (0) | 2021.10.10 |
댓글 영역