20 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 s) {  
        Stack<Integer> stk = new Stack<Integer>();  
        for (int i = 0; i < s.length(); ++i) {  
            int pos = "(){}[]".indexOf(s.substring(i, i + 1));  
            if (pos % 2 == 1) {  
                if (stk.isEmpty() || stk.pop() != pos - 1)  
                    return false;  
            } else {  
                stk.push(pos);  
            }  
        }  
        return stk.isEmpty();  
    }  
}  

 

 

 

解题思路:判断括号匹配的合法性。使用一个栈来解决问题。遇到左括号入栈,遇到右括号,检查栈顶的左括号是否匹配,如果匹配,弹栈,如果不匹配,返回错误。如果栈为空,而遇到右括号,同样返回错误。遍历完后,栈如果不空,同样返回错误。

class Solution:
    # @return a boolean
    def isValid(self, s):
        stack = []
        for i in range(len(s)):
            if s[i] == '(' or s[i] == '[' or s[i] == '{':
                stack.append(s[i])
            if s[i] == ')':
                if stack == [] or stack.pop() != '(':
                    return False
            if s[i] == ']':
                if stack == [] or stack.pop() != '[':
                    return False
            if s[i] == '}':
                if stack == [] or stack.pop() != '{':
                    return False
        if stack:
            return False
        else:
            return True

 

posted @ 2016-03-15 16:47  zxqstrong  阅读(173)  评论(0编辑  收藏  举报