【LeetCode】20. Valid Parentheses 解题报告(Python)

题目分析:

这一题是匹配括号的问题,用栈去匹配可以解决。

代码说明:
1、这如果res里有元素且和下一个括号匹配,那就删除res最后一位,res是栈,i是res的长度。

 if i > 0 and c == ')' and res[i - 1] == '(':
                res = res[:i - 1]
                i -= 1

2、其他情况入栈,同时标记栈长度加一。

else:
                res += c
                i += 1

3、return res == ''栈为空就是匹配成功,否则不成功。

测试代码:

class Solution:
    def isValid(self, s):
        res = ''
        i = 0
        for c in s:
            if i > 0 and c == ')' and res[i - 1] == '(':
                res = res[:i - 1]
                i -= 1
            elif i > 0 and c == ']' and res[i - 1] == '[':
                res = res[:i - 1]
                i -= 1
            elif i > 0 and c == '}' and res[i - 1] == '{':
                res = res[:i - 1]
                i -= 1
            else:
                res += c
                i += 1
        return res == ''
        
print(Solution().isValid('{({})[]{}}{[()]}'))   #提交时请删除该行

猜你喜欢

转载自blog.csdn.net/L141210113/article/details/88070400
今日推荐