
Algorithm Classification : stack
Difficulty Level : easy
Source : LeetCode - 20. Valid Parentheses


first, I use stack algorithm.
if index of 'String s' is '(' or '{' or '[', push it.
and then if index of 'String s' is ')' or '}' or ']', check stack.if last stack is each '(' or '{' or '[', pop it.
but else, return falseAt last, check the size of the stack. If the stack's size is not 0, return false; otherwise, return true.
import java.util.Stack;
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for(int i=0;i<s.length();i++) {
if(s.charAt(i)=='(' || s.charAt(i)=='{' || s.charAt(i)=='[')
stack.add(s.charAt(i));
else if(stack.empty())
return false;
else if(s.charAt(i)==')' && stack.pop()=='(');
else if(s.charAt(i)=='}' && stack.pop()=='{');
else if(s.charAt(i)==']' && stack.pop()=='[');
else return false;
}
if(stack.empty())
return true;
else
return false;
}
}


A few exceptions should be considered well.
ex) [, [](, [(])