leetcode题目之括号匹配问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36470920/article/details/84981681

关于括号匹配问题,提到这个问题就会想到数据结构栈,关于括号匹配大家也都是熟悉不过了,不过今天刷起这道题,还是让我花了一些时间去回忆这里面的一些细节,尤其是用python去复现的时候。

首先看一下问题描述:

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

我用python中的栈这个数据结构去实现,具体以list类型来达到最终效果,首先明白list使用实现栈的细节:

list中的append()方法相当于进栈操作,pop()方法相当于出栈操作,个人不建议使用remove(list[-1])这种方法,因为会导致列表元素顺序发生变化,比如:

l = ['[','(','[']
print(l)
l.remove(l[-1])
print(l)

运行如上代码,会发现列表 l 的前两个元素的位置发生了变化,会导致结果出错

接下来还是说下这道题用栈数据结构去解决的思想:

当遇到左括号('('、'['、'{')输入的时候,就进栈,当遇到右括号的时候,然后观察栈顶元素是不是与之相匹配的左括号,如果是,将栈顶元素出栈,如果不是则报错。最后检验是否栈为空,如果不为空,报错。

接下来贴上我的代码吧:

#-*-:Coding:UTF-8-*-
class Solution:
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        l = []
        for i in range(len(s)):
            if s[i] == '(':
                l.append(s[i])
                print(l)
            if s[i] == '[':
                l.append(s[i])
                print(l)
            if s[i] == '{':
                l.append(s[i])
                print(l)
            if s[i] == ')':
                if len(l) == 0:
                    return False
                if l[-1] != '(':
                    return False
                else:
                    l.pop()
                    print(l)
            if s[i] == ']':
                if len(l) == 0:
                    return False
                if l[-1] != '[':
                    return False
                else:
                    l.pop()
                    print(l)
            if s[i] == '}':
                if len(l) == 0:
                    return False
                if l[-1] != '{':
                    return False
                else:
                    l.pop()
                    print(l)
        if len(l) != 0:
            return False
        else:
            return True

if __name__ == '__main__':
    S = Solution()
    obj = input("")
    print(S.isValid(obj))

我的代码处理比较繁琐,因为考虑到这样一种情况,就是如果输入的字符串只有右括号,那么我的初始栈就是空的,所以要刚开始发现是空栈但是有右括号要进行匹配时,就果断输出False。

接下来是运行结果图:

 

好了,到这儿就结束了!谢谢观看!

2018.12.13 2:07 am 

猜你喜欢

转载自blog.csdn.net/qq_36470920/article/details/84981681