1. 程式人生 > >【棧操作&括號匹配】Valid Parentheses

【棧操作&括號匹配】Valid Parentheses

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.

public class Solution {
    public boolean isValid(String str) {
        if(str == null || str.length()==0) return true;
        Stack<Character> s = new Stack<Character>();
        int len = str.length();
        for(int i=0; i<len; i++){
            char c = str.charAt(i);
            if(c=='('|| c=='{' || c== '[') s.push(c);
            else if(!s.isEmpty()){
                if(c==')' && s.peek()=='(') s.pop();
                else if(c==']' && s.peek()=='[') s.pop();
                else if(c=='}' && s.peek()=='{') s.pop();
                else s.push(c);
            }
            else return false;
        }
        if(s.isEmpty()) return true;
        return false;
    }
}