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
代码来自:https://leetcode.com/problems/wildcard-matching/discuss/
几种情况:
一:遇到“*” 就记录此时s及p的位置istar及jstar,s向后移,p保持“*”。
二:当s[i]=p[j]或者p[j] = "?"时,就同时向后移,(不在if,也不在else的if中出现,就默认自动同时向后移)
三:遇到s[i] != p[j],而且p也不等于“?”,此时发生不匹配,那就判断p中是否有已出现过“*”,若p中出现过“*”,p回到"*"的位置jstar,s回到istar+1.
class Solution {
public:
bool isMatch(string s, string p) {
int slen = s.size(), plen = p.size(), i, j, iStar=-1, jStar=-1;
for(i=0,j=0 ; i<slen; ++i, ++j)
{
if(p[j]=='*') //meet a new '*', update traceback i/j info
{
iStar = i;
jStar = j;
--i;
}
else
{
if(p[j]!=s[i] && p[j]!='?')
{ // mismatch happens
if(iStar >=0) // met a '*' before, then do traceback
{
i = iStar++;
j = jStar;
}
else return false; // otherwise fail
}
}
}
while(p[j]=='*') ++j;
return j==plen;
}
};