题目:44. 通配符匹配
链接:https://leetcode-cn.com/problems/wildcard-matching/description/
给定一个字符串 (s
) 和一个字符模式 (p
) ,实现一个支持 '?'
和 '*'
的通配符匹配。
'?' 可以匹配任何单个字符。 '*' 可以匹配任意字符串(包括空字符串)。
这个跟第十题(10. Regular Expression Matching)很像啊,写了递归超时了,然后改成了DP过了。
python:
class Solution: def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ dp=[[False for col in range(len(p)+1)]for row in range(len(s)+1)] dp[0][0]=True for i in range(len(s)+1): for j in range(1,len(p)+1): if p[j-1]=="*": dp[i][j]=dp[i][j-1] or (i>0 and dp[i-1][j]) else: dp[i][j]=i>0 and dp[i-1][j-1] and (s[i-1]==p[j-1] or p[j-1]=="?") return dp[len(s)][len(p)] # if not p: # return not s # if len(p)==1: # if p[0]=="*": # return True # else: # return len(s)==1 and (s[0]==p[0] or p[0]=="?") # if p[0]!="*": # if not s: # return False # else: # return (p[0]==s[0] or p[0]=="?") and self.isMatch(s[1:len(s)],p[1:len(p)]) # else: # while len(s)!=0: # if self.isMatch(s,p[1:len(p)]): # return True # s=s[1:len(s)] # return self.isMatch(s,p[1:len(p)])