Description:
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
The brackets must close in the correct order, "()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.
Solution:
This problem can be solved by a stack structure. Every time we meet the left one, we try to push it into the stack; and when it comes to a right one, we get the top one one stack and find if they are a match, if not then return false.
import java.util.Stack;
public class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack();
char ch, top;
for (int i = 0; i < s.length(); i++) {
ch = s.charAt(i);
if (ch == '(' || ch == '[' || ch == '{')
stack.push(ch);
else {
if (stack.empty())
return false;
top = stack.pop();
if (ch == ')' && top != '(') {
return false;
} else if (ch == ']' && top != '[') {
return false;
} else if (ch == '{' && top != '}')
return false;
}
}
if (stack.empty())
return true;
else
return false;
}
}