Skip to content

Instantly share code, notes, and snippets.

@qkreltms
Created March 30, 2018 13:05
Show Gist options
  • Select an option

  • Save qkreltms/51665f5e94a8b14ee03c63e73ffde554 to your computer and use it in GitHub Desktop.

Select an option

Save qkreltms/51665f5e94a8b14ee03c63e73ffde554 to your computer and use it in GitHub Desktop.
백준9012번 stack 버전 https://www.acmicpc.net/problem/9012
class Stack:
def __init__(self, length):
self.d = [None] * length
self.top = -1
def len(self):
return self.top+1
def append(self, item):
self.top += 1
self.d[self.top] = item
def pop(self):
item = self.d[self.top]
self.top -= 1
if self.top < 0:
self.top = -1
return item
def is_empty(self):
return False if self.top >= 0 else True
def print(self):
print(self.d)
def f(stack):
if stack.len() <= 1:
print("NO")
return
temp = []
b = stack.pop()
a = stack.pop()
temp.append(b)
temp.append(a)
while True:
if a is '(' and b is ')':
temp.pop()
temp.pop()
if stack.is_empty():
print("YES")
return
while len(temp):
stack.append(temp.pop())
if stack.len() >= 2:
b = stack.pop()
a = stack.pop()
temp.append(b)
temp.append(a)
else:
print("NO")
return
else:
b = a
if stack.len() >= 2:
a = stack.pop()
else:
print("NO")
return
temp.append(a)
for i in range(int(input())):
stack = Stack(100001)
p = input()
for j in range(len(p)):
stack.append(p[j])
f(stack)
@qkreltms
Copy link
Author

()를 찾는다
((((((()))))))
(, )의 개수가 몇 개이던, ()같이 딱 붙어있는걸 찾는다.
()를 제거후 다시 ()를 찾는다...
만약 ()를 다 제거해도 어떤값이 남아있다면 print("NO")

@qkreltms
Copy link
Author

for i in range(int(input())):
p = input()
if p.startswith(')') or p.endswith('('):
print("NO")
else:
print("YES") if len(''.join(p.split('('))) is len(''.join(p.split(')'))) else print("NO")
처음에는 각 괄호의 개수를 구한 후 쌍이 맞으면 YES를 출력하려고 했으나
())(() 이 반례의 경우에 원하는 결과가 나오지 않는다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment