[LeetCode]020. 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.

Solution: use a stack to store the left parentheses, if there is a right parentheses, compare it with the pop of the stack. 

Running time: O(n).

注意:字符串里只含有括号。遍历字符串后,需再次判断栈是否为空,此时为空,才说明一一配对。


public class Solution {
    public boolean isValid(String s) {
        // Start typing your Java solution below
        // DO NOT write main() function
        Stack st = new Stack();
        int len = s.length();
        for(int i=0; i<len;i++){
            char value = s.charAt(i);
            if(value =='(' || value == '[' || value == '{'){
                st.push(value);
            }else{
                if (st.size() == 0){
                    return false;
                }
                if(value ==')'){
                    if((Character)st.pop() != '('){
                        return false;
                    }
                }
                if(value == ']'){
                    if((Character)st.pop() != '['){
                        return false;
                    }
                }
                if(value == '}'){
                    if((Character)st.pop() != '{'){
                        return false;
                    }
                }
            }
        }
        if(st.size() != 0){
            return false;
        }else{
            return true;
        }
    }
}


你可能感兴趣的:(LeetCode)