leetcode Wildcard Matching

Wildcard Matching

  Total Accepted: 14208  Total Submissions: 100593 My Submissions

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

class Solution {
public:
    bool isMatch(const char *s, const char *p) {
        const char* star=NULL; //最后一个‘*’的位置
        const char* ss=s;
        while (*s){
            if ((*p=='?')||(*p==*s)){s++;p++;continue;} 

           
            if (*p=='*'){star=p++; ss=s;continue;} 

           
            if (star){
			
				p = star+1;
				s=++ss;continue;
			} //这里其实就是递归的思想,不过返回比较快,算了一下,极限情况下比较次数为:
             //l2 * (l1-l2),一个*,后面一片a,长度最长的为3W多,乘一下也就4.5e8,不过貌似没这种样例
            return false;
        }
        while (*p=='*'){p++;}
        return !*p;  
    }
};


你可能感兴趣的:(leetcode)