Input : "{[]}"
Output : true
Input : "([)]"
Output : false
Input : "(){}[]"
Output : true
Input : "(]"
Output : false
package stack_queue;
import java.util.*;
public class ValidParentheses {
public static void main(String[] args){
//String exp="{({})}";
String exp = "([)]";
System.out.println(isValid(exp));
}
public static boolean isValid(String s){
//1 error check (괄호는 늘 쌍으로 이루어지기에 홀수 갯수라면 무조건 false 리턴)
if(s.length()%2 != 0) return false;
Stack<Character> stack = new Stack<>();
//2 경우에 따라 나눠줄 수 있도록 반복문 돌려서 체크
for(int i=0; i<s.length(); i++){
switch(s.charAt(i)){
case ')':
if(!stack.empty() && stack.peek()=='(') stack.pop();
break;
case '}':
if(!stack.empty() && stack.peek()=='{') stack.pop();
break;
case ']':
if(!stack.empty() && stack.peek()=='[') stack.pop();
break;
default:
stack.push(s.charAt(i));
break;
}
}
return stack.empty();
}
}