20 Valid Parentheses

使用栈进行括号匹配的判断,如果需要的多,可以使用hash表预存储

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        d = {
            '(' : ')',
            '{' : '}',
            '[' : ']'
        }
        length = len(s)
        st = []
        for i in range(length):
            if s[i] in ['(', '{', '[']:
                st.append(s[i])
            else:
                if len(st) == 0 or d[st[-1]] != s[i]:
                    return False
                else:
                    st.pop()
        if st == []:
            return True
        else:
            return False

results matching ""

    No results matching ""