判断两个可能包含通配符“?”和“*”的字符串是否匹配。匹配规则如下:
两个串完全匹配才算匹配成功。
样例1
输入:
"aa"
"a"
输出: false
输出2
输入:
"aa"
"aa"
输出: true
输出3
输入:
"aaa"
"aa"
输出: false
输出4
输入:
"aa"
"*"
输出: true
说明: ‘*‘ 可以替换任何字符串
输出5
输入:
"aa"
"a*"
输出: true
样例6
输入:
"ab"
"?*"
输出: true
说明: ‘?‘ -> ‘a‘ ‘*‘ -> ‘b‘
样例7
输入: "aab" "c*a*b" 输出: false
class Solution:
"""
@param s: A string
@param p: A string includes "?" and "*"
@return: is Match?
"""
def isMatch(self, s, p):
# write your code here
self.cache = {}
return self.helper(s, p, s_at=len(s)-1, p_at=len(p)-1)
def helper(self, s, p, s_at, p_at):
if (s_at, p_at) in self.cache:
return self.cache[(s_at, p_at)]
if p_at < 0:
return s_at < 0
if s_at < 0:
for i in range(0, p_at+1):
if p[i] != "*":
return False
return True
if p[p_at] == ‘?‘:
is_match = self.helper(s, p, s_at-1, p_at-1)
elif p[p_at] == ‘*‘:
is_match = self.helper(s, p, s_at-1, p_at) or self.helper(s, p, s_at, p_at-1)
else:
is_match = s_at >= 0 and s[s_at]==p[p_at] and self.helper(s, p, s_at-1, p_at-1)
self.cache[(s_at, p_at)] = is_match
return is_match
注意 如果不用cache的话会超时。
原文:https://www.cnblogs.com/bonelee/p/11707288.html