Hard-题目51：44. Wildcard Matching

189人阅读 评论(0)

Implement wildcard pattern matching with support for ‘?’ and ‘*’.

‘?’ Matches any single character.
‘*’ Matches any sequence of characters (including the empty sequence).

The matching should cover the entire input string (not partial).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
isMatch(“aa”,”a”) → false
isMatch(“aa”,”aa”) → true
isMatch(“aaa”,”aa”) → false
isMatch(“aa”, “*”) → true
isMatch(“aa”, “a*”) → true
isMatch(“ab”, “?*”) → true
isMatch(“aab”, “c*a*b”) → false

Loop
keep two pointers in S and P here i and j
if S[i] == P[j] or P[j] == ‘?’ we keep moving
if ‘*’ exist in P then we mark the position in P as star and mark position in s as s_star
Loop over s until S[i] == P[star + 1] otherwise False

class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
i = 0
j = 0
star = -1
s_star = 0
s_len = len(s)
p_len = len(p)
while i < s_len:
if i < s_len and j < p_len and (s[i] == p[j] or p[j] == '?'):
i += 1
j += 1
elif j < p_len and p[j] == '*':
star = j
s_star = i
j += 1
elif star != -1:
j = star + 1
s_star += 1
i = s_star
else:
return False
while j < p_len and p[j] == '*':
j += 1
return j == p_len

116ms,85.49%,124ms,7.50%
cmershen的碎碎念：

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：64404次
• 积分：3285
• 等级：
• 排名：第10717名
• 原创：270篇
• 转载：53篇
• 译文：0篇
• 评论：8条
文章分类
阅读排行
最新评论