问题:给定两个字符串s和p,s是小写字母组成的字符串,p中除了小写字母外,还可能有“?”和“*”。判断按照正则表达式的规则,p能否和s匹配成功。("?"匹配任意单个字符,"*"匹配多个任意字符,包括空字符)
示例:
输入:s = "bb" p = "b"
输出:False
输入:s = "ab" p = "*"
输出:True
输入:s = "dr" p = "r?"
输出:False
输入:s = "abcde" p = "a*c*
输出:True
解决思路:
# 根据p和s是否为空进行判断,为空输出相应的结果
# s和p都不为空,从两端逐个判断p的单个子字符是否等于s的单个子字符或者是否为“?”和“*”,如果相等或者为“?”,则缩短两者
# 再次判断p和s是否为空
# 当p和s都不为空,p的两端如果不是*,则返回False,如果是“*”,使用“*”分割p,再进一步判断子字符串是否依次在s中出现,注意“?”也是满足条件的
Python代码:
class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ if not p: return not s if not s: return p == len(p)*"*" i = 0 while i < len(p) and i < len(s): if p[i] in [s[i],"?"]: i += 1 else: break p = p[i:] s = s[i:] j = len(p)-1 k = len(s)-1 while j >= 0 and k >= 0: if p[j] in[s[k],"?"]: j -= 1 k -= 1 else: break p = p[:j+1] s = s[:k+1] if not p: return not s if not s: return p == len(p)*"*" if p[0] != "*" or p[-1] != "*": return False else: lp = p.split("*") for sub in lp: if sub: flag = False for j in range(len(s)-len(sub)+1): if sub[0] in [s[j],"?"]: if self.Match(s[j:j+len(sub)],sub): flag = True s = s[j+len(sub):] break if not flag: return False return True def Match(self,a,b): for i in range(len(a)): if b[i] not in [a[i],"?"]: return False return True