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
題意
實現?和*的通配符模式匹配
?可以替換任意單字符
*可以匹配任意字符序列,包括空序列
通配符正好可以匹配輸入字符串
題解
難度在於*可以匹配一段字符串,所以如果p中包含有*,則做一個標記,把s中與p的*後面的字符不匹配的過濾掉
所以根據*p分三種情況: *p是?時 s和p都接着往下遍歷
*p是*時,做一個標記,表示*p前有*; 同時記錄*的位置和當前s的位置
*p是其他字符時,如果前邊沒有*並且當前字符不匹配,則返回錯誤 ; 如果前邊有*,p要篩選s(篩選的過程是這樣,*後面的字符與s的進行逐一匹配,如果匹配失敗,則過濾掉一個s)
class Solution {
public:
bool isMatch(string s, string p) {
bool start=false;
const char *scur,*pcur,*ss,*pp;
for(scur=&s[0],pcur=&p[0];*scur!='\0';scur++,pcur++)
{
switch(*pcur)
{
case '?':
break;
case '*':
start=true;
ss=scur;
pp=pcur;
while(*pp=='*') pp++;//連續的*是一樣的效果
if(*pp=='\0') return true;
scur=ss-1;//相當於下一輪s的位置不變
pcur=pp-1;//把下一輪的p置於*的後面
break;
default :
if(*pcur!=*scur)
{
if(!start) return false;
ss++;
scur=ss-1;//s往前遍歷,p保持在*後面
pcur=pp-1;
}
break;
}
}
while(*pcur=='*') pcur++;
return *pcur=='\0';
}
};