https://level.goorm.io/exam/49076/1%EC%B0%A8%EC%9B%90-%EB%BF%8C%EC%9A%94%EB%BF%8C%EC%9A%94/quiz/1
from collections import deque
N, M = map(int, input().split())
S = input()
S = list(S)
def bb(S):
stack = []
result = []
S = deque(S)
if len(set(S)) == 1 and len(S)>1:
return 'CLEAR!'
while S:
elem = S.popleft()
if stack:
if stack[-1] == elem:
stack.append(elem)
if not S:
if len(stack) >= M:
return result
else:
if len(stack) >= M:
result.append(elem)
result += list(S)
return result
else:
result += stack[:]
stack = []
stack.append(elem)
else:
stack.append(elem)
result += stack[:]
return result
while True:
if S != bb(S):
if bb(S) != 'CLEAR!':
S = bb(S)
else:
print(bb(S))
break
else:
ans = bb(S)
print(''.join(ans))
break
import sys
input = sys.stdin.readline
N, M = map(int, input().split())
S = input().rstrip()
Q = []
Q.append(('', 1))
S += 'z'
for c in S:
if Q[-1][0] != c:
if M <= Q[-1][1]:
top = Q[-1][0]
while top == Q[-1][0]:
Q.pop()
if Q[-1][0] == c:
Q.append((c, Q[-1][1] + 1))
else:
Q.append((c, 1))
Q.pop()
if len(Q) > 1:
for c, n in Q:
print(c, end='')
else:
print("CLEAR!")
이것저것 조건을 달다보니 코드가 길어졌는데 정답 코드처럼 간소화할 수 있는 문제였다.