예제 입력:
So when I die (the [first] I will see in (heaven) is a score list).
[ first in ] ( first out ).
Half Moon tonight (At least it is better than no Moon at all].
A rope may form )( a trail in a maze.
Help( I[m being held prisoner in a fortune cookie factory)].
([ (([( [ ] ) ( ) (( ))] )) ]).
.
.
예제 출력:
yes
yes
no
no
no
yes
yes
스택(Stack): 후입선출(Last In First Out)로 pop()수행시 나중에 push()된 데이터가 먼저 나온다.
while(true) {
s=sc.nextLine();
if(s.equals(".")) {
break;
}
}
if(c=='('||c=='[') {
stack.push(c);
}
if(stack.isEmpty()||stack.peek()!='(') {
return "no";
}
else {
stack.pop();
}
if(stack.isEmpty()||stack.peek()!='[') {
return "no";
}
else {
stack.pop();
}
코드
import java.util.*;
public class No_4949 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String s="";
while(true) {
s=sc.nextLine();
if(s.equals(".")) {
break;
}
System.out.println(solution(s));
}
}
public static String solution(String s) {
Stack<Character> stack =new Stack<>();
for(int i=0;i<s.length();i++) {
char c=s.charAt(i);
if(c=='('||c=='[') {
stack.push(c);
}
else if(c==')') {
if(stack.isEmpty()||stack.peek()!='(') {
return "no";
}
else {
stack.pop();
}
}
else if(c==']') {
if(stack.isEmpty()||stack.peek()!='[') {
return "no";
}
else {
stack.pop();
}
}
}
if(stack.isEmpty()) {
return "yes";
}
else {
return "no";
}
}
}
실행 결과