LeetCode_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

  方法一: 主要是*的匹配问题。p每遇到一个*,就保留住当前*的坐标和s的坐标,然后s从前往后扫描,如果不成功,则s++,重新扫描。

class Solution {
public:
    bool isMatch(const char *s, const char *p) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
    bool star = false;
      const char *sp, *pp;
      for(sp = s, pp = p; *sp != ''; sp++,pp++ )
      {
        switch(*pp)
        {
            case '?':{
                break;
            }
            case '*':{
                star = true;
                s = sp;p = pp;
                while(*p == '*')p++;
                if('' == *p) return true;
                //* match zero element 
                sp = s-1;
                pp = p-1;
                break;
            }
            default:{
                if(*sp == *pp) break;
                
                if(star == true){
                  sp = s;
                  pp = p-1;
                  s++;
                }else
                   return false;
            }
        }
      }
      while(*pp == '*')pp++;
      return *pp == '';
    }
};

 方法二: 递归,不过大数据超时

class Solution {
public:
    bool isMatch(const char *s, const char *p) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
     if(*s == '' && *p == '') return true;
     if(*s == ''){
        while(*p == '*')p++;
        return *p == '' ;
     }
     if(*p == '') return false;
     
     if(*p == '?') return isMatch(s+1,p+1);
     if(*p == '*'){
        while(*p == '*')p++;
        if(*p == '') return true;
        return isMatch(s ,p) || isMatch(s+1,p) ||
                              isMatch(s+1,p-1);
    }
     return *p == *s  && isMatch(s+1,p+1) ;
    }
};
View Code

上述代码中: isMatch(s ,p): *匹配了零个元素;isMatch(s+1 ,p) :匹配了一个元素 ;isMatch(s +1,p-1) : 匹配了多个元素

原文地址:https://www.cnblogs.com/graph/p/3234781.html