leetcode 20.有效的括号

给定一个只包括 '('')''{''}''['']' 的字符串,判断字符串是否有效。

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。

注意空字符串可被认为是有效字符串。

 1 class Solution:
 2     def isValid(self, s):
 3         """
 4         :type s: str
 5         :rtype: bool
 6         
 7         """
 8        
 9         if len(s) == 0:
10             return True
11         if len(s) % 2 == 0:
12             """
13             parts = ['()', '{}', '[]']
14             for part in parts:
15                 s = s.replace(part, '')
16             if s == '':
17                 return True
18             else:
19                 return False
20             
21         else:
22             return False
23         """
24             while '()' in s or '{}' in s or '[]' in s:
25                 s = s.replace('()','').replace('{}','').replace('[]','')
26                 
27             if s =='':
28                 return True
29             else:
30                 return False
31         else:
32             return False

replace()函数把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。

str.replace(old, new[, max])

原文地址:https://www.cnblogs.com/chengchengaqin/p/9510794.html