题意
判断输入的字符串是否合法。输入的字符串只包含“()[]{}”
要求所有的括号都被正确的关闭。
另外,空字符串也是合法的。
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
思路
题目难度是easy,但是很有些需要思考的地方。
最早的想法是通过双指针,从两边判断是否是一对括号。但是遇到类似"{}[]"的用例就不太好处理。
重新观察符合条件的字符串,发现不管怎样复杂的嵌套,肯定会有一对括号挨在一起。
把这一对从字符串中移除,剩下的字符串同样符合条件。
解决
1 class Solution: 2 def isValid(self, s): 3 if s == "" : return True 4 m = 0 5 n = 1 6 while n < len(s): 7 if self.isPair(s[m], s[n]) : 8 if len(s) == 2 : return True 9 return self.isValid(s[0: m] + s[n+1: len(s)]) 10 m += 1 11 n += 1 12 return False 13 14 15 def isPair(self, s1, s2): 16 return s1 == '(' and s2 == ')' or s1 == '[' and s2 == ']' or s1 == '{' and s2 == '}'
思考
问题虽然解决了,但是O(n2)的复杂度肯定是不完美的。回头看这道题的时候Leetcode已经有了解答。
利用了stack后进先出的特点,配合hashmap解决。时间复杂度可以达到O(n)
1 class Solution: 2 def isValid(self, s): 3 dic = {'(' : ')', '{' : '}', '[' : ']'} 4 stack = [] 5 for char in s: 6 if char in dic: 7 stack.append(char) 8 else: 9 if not stack or dic[stack.pop()] != char: 10 return False 11 return not stack