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.
java code : 典型栈的应用
public class Solution {
public boolean isValid(String s) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if((s.length() & 1) == 1)
return false;
Stack<Character> st = new Stack<Character>();
for(int i = 0; i < s.length(); i++)
{
if(i == 0 || isLeft(s.charAt(i)))
st.add(s.charAt(i));
else
{
if(st.isEmpty())
return false;
if(isMatch(st.peek(), s.charAt(i)))
st.pop();
else return false;
}
}
return st.isEmpty();
}
public boolean isLeft(char ch)
{
if(ch == '(' || ch == '[' || ch == '{')
return true;
return false;
}
public boolean isMatch(char x, char y)
{
if((x == '(' && y == ')') || (x == '[' && y == ']') || (x == '{' && y == '}'))
return true;
return false;
}
}