Table of Content
题目:
这道题主要应用递归的思路来进行匹配,值得注意的是,在python里 and 操作的优先级是大于 or的,对递归不熟悉的朋友,不妨单步调试一下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
class Solution: def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ in_str = s pt = p if not pt: return not in_str first_match = bool(in_str) and pt[0] in {in_str[0], '.'} if len(pt) >= 2 and pt[1] == '*': return (self.isMatch(in_str, pt[2:]) or first_match and self.isMatch(in_str[1:], pt)) else: return first_match and self.isMatch(in_str[1:], pt[1:]) s = Solution() print(s.isMatch("ab", "c*ab")) |
如果您有更好的思路,欢迎讨论。