코딩테스트/Python
[프로그래머스] 짝지어 제거하기
yo~og
2021. 9. 8. 02:13
내 코드
def solution(s):
a = [s[0]]
i=1
while True:
if i==len(s) : break
if len(a)!=0 and a[-1] == s[i]:
a.pop(-1)
i+=1
else:
a.append(s[i])
i+=1
return 1 if len(a)==0 else 0
s를 a라는 스택에 하나씩 넣어주면서 풀었다.
스택의 가장 마지막이 s[i]와 같으면 스택의 가장 마지막 원소를 pop하고 i를 더한다. 다르면 스택에 s[i]를 넣고 i를 더한다.
다른사람 코드
def solution(s):
answer = []
for i in s:
if not(answer):
answer.append(i)
else:
if(answer[-1] == i):
answer.pop()
else:
answer.append(i)
return not(answer)
not(list)는 리스트가 비어있는지 확인해주는 함수이다. 비어있으면 True를 반환하고 아니면 False를 반환한다.
푸는 방법은 나와 비슷하다!