Wildcard Matching

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

1.递归-->超时

class Solution {
public:
    bool isMatch(string& s,int sSize,int startS,string& p,int pSize,int startP)
    {
        if(startP==pSize){
            return startS==sSize;
        }
        if(p[startP]=='*'){
            while(p[startP]=='*') startP++;
            while(startS<sSize){
                if(isMatch(s,sSize,startS,p,pSize,startP)){
                    return true;
                }
                startS++;
            }
            return isMatch(s,sSize,startS,p,pSize,startP) ;
        }else if((startS<sSize) && (p[startP]=='?' || p[startP]==s[startS])){
            return isMatch(s,sSize,startS+1,p,pSize,startP+1);
        }
        return false;
    }
    bool isMatch(string s, string p) {
        return isMatch(s, s.size(),0,p,p.size(),0);
    }
};

 2.迭代版

递归版之所以超时是因为同一个模式串和字符串进行了多次重复匹配,这种重复匹配主要是因为模式串中有多个*号,如果后面的*号所有的可能情况都比较了,但仍然不能匹配时,

我们需要回溯到前一个*号的位置,重新进行一次的比较。但事实上,这种回溯是没有必要的,下面我们分析一下原因,看下图(注:j和m之间可能还有*号):

其中m是p串的最后一个字符的位置,n是s串的最后一个字符的位置。

假设p串i-1之前的位置和s串k-1之前的位置都匹配,现在i位置是*号,我们假设*匹配s的k位置的字符,即先让*号匹配s串的一个字符,并且p[i+1...j-1]与s[k+1...h-1]匹配,

按递归的思路,如果p[j...m]与s[h...n]不匹配,我们要回溯,让p串的i字符跟s串k+1字符匹配,即*号匹配s串的两个字符,然后判段p[i+1...j-1]与s[k+2...h]是否匹配,如果匹配,再判断p[j...m]和s[h+1...n]是否匹配。

在这个过程中,我们发现,判断p[j...m]和s[h+1...n]是否匹配,是判段p[j...m]与s[h...n]是否匹配的子问题,也就是说,如果p[j...m]与s[h...n]不匹配时,p[j...m]和s[h+1...n]也肯定不匹配。

这就说明,我们其实没必要进行回溯。

class Solution {
public:
    bool isMatch(string s, string p) {
        int starPos=-1,sPos = -1;
        int sSize = s.size();
        int pSize = p.size();
        int i=0,j=0;
        while(i<sSize ){
            cout<<"p[j]="<<p[j]<<endl;
            if(p[j]=='?' || p[j]==s[i]){
                i++;j++;
                continue;
            }
            if(p[j]=='*'){
                starPos=j++;
                sPos = i;
                continue;
            }
            if(starPos!=-1){
                j=starPos+1;
                i = ++sPos;
                continue;
            }
            return false;
        }
        while(j<pSize && p[j]=='*') j++;
        return (j==pSize && i==sSize) ? true:false;
    }
};

参考:

http://blog.csdn.net/doc_sgl/article/details/12721187

http://www.xuebuyuan.com/1936978.html

原文地址:https://www.cnblogs.com/zengzy/p/5019079.html