https://leetcode.com/problems/valid-parentheses/
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
s consists of parentheses only '()[]{}'.
과거에 두세번 풀어봤던 올바른 괄호 문제이다. stack을 이용해서 풀면 된다.
import java.util.Stack;
class Solution {
public boolean isValid(String s) {
boolean answer = false;
char[] arr = s.toCharArray();
Stack<Character> stack = new Stack<>();
for (char c : arr) {
switch (c) {
case ')':
if (stack.isEmpty() || stack.pop() != '(')
return answer;
break;
case '}':
if (stack.isEmpty() || stack.pop() != '{')
return answer;
break;
case ']':
if (stack.isEmpty() || stack.pop() != '[')
return answer;
break;
default:
stack.push(c);
}
}
answer = (stack.isEmpty()) ? true : false;
return answer;
}
}