# 通配符匹配
给定一个字符串 (s
) 和一个字符模式 (p
) ,实现一个支持 '?'
和 '*'
的通配符匹配。
'?' 可以匹配任何单个字符。'*' 可以匹配任意字符串(包括空字符串)。
两个字符串完全匹配才算匹配成功。
说明:
s
可能为空,且只包含从 a-z
的小写字母。p
可能为空,且只包含从 a-z
的小写字母,以及字符 ?
和 *
。示例 1:
输入:s = "aa"p = "a"
输出: false
解释: "a" 无法匹配 "aa" 整个字符串。
示例 2:
输入:s = "aa"p = "*"
输出: true
解释: '*' 可以匹配任意字符串。
示例 3:
输入:s = "cb"p = "?a"
输出: false
解释: '?' 可以匹配 'c', 但第二个 'a' 无法匹配 'b'。
示例 4:
输入:s = "adceb"p = "*a*b"
输出: true
解释: 第一个 '*' 可以匹配空字符串, 第二个 '*' 可以匹配字符串 "dce".
示例 5:
输入:s = "acdcb"p = "a*c?b"以下程序实现了这一功能,请你填补空白处内容: ```python class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ s_index, p_index = 0, 0 star, s_star = -1, 0 s_len, p_len = len(s), len(p) while s_index < s_len: if p_index < p_len and (s[s_index] == p[p_index] or p[p_index] == '?'): s_index += 1 p_index += 1 ______________________; elif star != -1: p_index = star + 1 s_star += 1 s_index = s_star else: return False while p_index < p_len and p[p_index] == '*': p_index += 1 return p_index == p_len if __name__ == '__main__': s = Solution() print (s.isMatch(s = "aa",p = "a")) ``` ## template ```python class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ s_index, p_index = 0, 0 star, s_star = -1, 0 s_len, p_len = len(s), len(p) while s_index < s_len: if p_index < p_len and (s[s_index] == p[p_index] or p[p_index] == '?'): s_index += 1 p_index += 1 elif p_index < p_len and p[p_index] == '*': star = p_index s_star = s_index p_index += 1 elif star != -1: p_index = star + 1 s_star += 1 s_index = s_star else: return False while p_index < p_len and p[p_index] == '*': p_index += 1 return p_index == p_len if __name__ == '__main__': s = Solution() print (s.isMatch(s = "aa",p = "a")) ``` ## 答案 ```python elif p_index < p_len and p[p_index] == '*': star = p_index s_star = s_index p_index += 1 ``` ## 选项 ### A ```python elif p_index > p_len and p[p_index] == '*': star = p_index s_star = s_index p_index += 1 ``` ### B ```python elif p_index < p_len and p[p_index] == '*': star = p_index s_star = s_index p_index += s_star ``` ### C ```python elif p_index > p_len and p[p_index] == '*': star = p_index s_star = s_index p_index += s_star ```
输出: false