Source
https://school.programmers.co.kr/learn/courses/30/lessons/12909
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
Code
from collections import deque
def solution(s):
stack = [i for i in s]
queue = deque()
for i in range(len(stack)):
if queue:
char = stack.pop()
if char == '(' and queue[0] == ')':
queue.popleft()
else:
queue.append(char)
else:
queue.append(stack.pop())
if queue:
return False
else:
return True
How to solve?
Stack과 Queue를 하나씩 만들어서 Stack에서 pop한 괄호가 Queue와 페어가 맞다면 삭제하는 방식으로 코드를 작성했다.
One step more
1. 입력되는 string인 s를 그대로 이용해서 stack과 queue를 두개 선언하지 않고 공간최적화를 할 수 있다.
l = []
for char in s:
...
2. try ~ catch로 exception 처리를 해서 False를 내보낼 수 있다.
try:
l.pop()
except IndexError:
return False
3. return으로 len(l) == 0 을 사용해서 문맥을 간단하게 만들 수 있다.
return len(l) == 0'Problem solve' 카테고리의 다른 글
| [Leetcode] Longest Substring Without Repeating Characters (Javascript) (0) | 2023.03.21 |
|---|---|
| [Leetcode] Permutations (Python) (0) | 2023.03.21 |
| [Leetcode] Letter Combinations of a Phone Number (Python) (0) | 2023.03.19 |
| [Leetcode] Two Sum (JavaScript) (0) | 2023.03.16 |
| [프로그래머스] 게임 맵 최단거리 (Python) (2) | 2023.03.14 |