您的位置:首页 > 其它

44. Wildcard Matching (String; Recursion)

2015-10-05 19:07 357 查看
Implement wildcard pattern matching with support for
'?'
and
'*'
.

'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).不同于正则表达式中的*

*正则表达式的定义:

'.' Matches any single character.

'*' Matches zero or more of the preceding element.

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

思路:当遇到*,可能匹配0, 1, 2, ...个字符=>带回溯的递归

class Solution {
public:
bool isMatch(string s, string p) {
star = false;
return recursiveCheck(s,p,0,0);
}

bool recursiveCheck(const string &s, const string &p, int sIndex, int pIndex){
if(sIndex >= s.length()){
while(p[pIndex] == '*' && pIndex < p.length()) pIndex++; //s has went to end, check if the rest of p are all *
return (pIndex==p.length());
}

if(pIndex >= p.length()){
return checkStar(s,p);
}

switch(p[pIndex]) //p: pattern,在p中才可能出现?, *
{
case '?':
return recursiveCheck(s, p, sIndex+1, pIndex+1);
break;
case '*': //如果当前为*, 那么可认为之前的字符都匹配上了,并且将p移动到 * 结束后的第一个字符
star = true;  //p 每次指向的位置,要么是最开始,要么是 * 结束的第一个位置
starIndex = pIndex;
matchedIndex = sIndex-1;
while(p[pIndex] == '*'&& pIndex < p.length()){pIndex++;} //忽略紧接在 *后面的*
if(pIndex==p.length()) return true;//最后一位是*
return recursiveCheck(s,p,sIndex,pIndex); //*匹配0个字符
break;
default:
if(s[sIndex] != p[pIndex]) return checkStar(s, p);
else return recursiveCheck(s, p, sIndex+1, pIndex+1);
break;
}
}

bool checkStar(const string &s, const string &p){
if(!star) return false;
else {
int pIndex = starIndex+1;
int sIndex = ++matchedIndex; //回溯,*d多匹配一个字符
return recursiveCheck(s, p, sIndex, pIndex);
}
}
private:
int starIndex;
int matchedIndex;
bool star;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: