输入字符串s,p,p中可能包含字符"."和"*":使用正则表达式的规则判断s和p是否匹配
示例:
输入:s="abc" p =".*c"
输出:True
Python解决方案:
class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ len_p = len(p) len_s = len(s) if len_p == 0: return len_s == 0 judge = len_s > 0 and p[0] in [".",s[0]] if len_p > 1 and p[1] == "*": if judge: return self.isMatch(s[1:],p) or self.isMatch(s,p[2:]) else: return self.isMatch(s,p[2:]) else: return judge and self.isMatch(s[1:],p[1:])
改进方案(转自leetcode用csler):
class Solution: def __init__(self): self.cache = {} def isMatch(self, s: 'str', p: 'str') -> 'bool': if len(p) == 0: return len(s) == 0 question = s + '+' + p if question in self.cache: return self.cache[question] firstMatch = len(s) > 0 and (p[0] == s[0] or p[0] == '.') if len(p) > 1 and p[1] == '*': if firstMatch: res = self.isMatch(s[1:], p) or self.isMatch(s, p[2:]) else: res = self.isMatch(s, p[2:]) else: res = firstMatch and self.isMatch(s[1:], p[1:]) self.cache[question] = res return res