https://www.acmicpc.net/problem/4949
while True:
x=input().rstrip()
if x=='.':
break
stack=[]
result=True
for i in x:
if i=='[' or i=='(':
stack.append(i)
elif i==']':
if not stack:
result=False
break
if stack[-1]=='[':
stack.pop()
else:
result=False
break
elif i==')':
if not stack:
result=False
break
if stack[-1]=='(':
stack.pop()
else:
result=False
break
if result and not stack:
print('yes')
else:
print('no')
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
private static void solution() throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int input_len;
Stack<Character> stack = new Stack<>();
char c;
String input;
while(!(input = br.readLine()).equals(".")) {
stack.clear();
input_len = input.length();
for(int i = 0; i < input_len; i++) {
c = input.charAt(i);
if(c == '(' || c == '[') { // (, [ 일 때 추가
stack.push(c);
}
else if(c == ')' || c == ']') { // ), ] 일 때
if(stack.isEmpty() || (c == ')' && stack.peek() != '(') || (c == ']' && stack.peek() != '[')) {
// 짝이 안맞는 경우 추가
stack.push(c);
break;
}
stack.pop(); // 짝이 맞으면 pop
}
}
if(stack.isEmpty()) {
System.out.println("yes");
}
else {
System.out.println("no");
}
}
}
public static void main(String[] args) throws Exception {
solution();
}
}
스택에 저장 후 괄호의 짝이 맞으면 yes, 아니면 no