LeetCode: Wildcard Matching

来源:互联网 发布:mysql 时间虚表 编辑:程序博客网 时间:2024/06/08 05:04

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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "*") → trueisMatch("aa", "a*") → trueisMatch("ab", "?*") → trueisMatch("aab", "c*a*b") → false
class Solution {public:    bool isMatch(const char *s, const char *p) {       const char *index1, *index2;       index1 = NULL;       index2 = NULL;       while(*s != NULL)       {           if(*s == *p)           {               s++;               p++;           }           else if(*p == '?')           {               p++;               s++;           }           else if(*p == '*')           {               index1 = s;               index2 = ++p;           }           else if(index1 != NULL)           {               s = ++index1;               p = index2;           }           else           {               return false;           }       }       while( *p != NULL)       {           if(*(p++) != '*')                return false;       }       return true;           }};



Round 2:

class Solution {public:    bool isMatch(const char *s, const char *p) {        const char *pres = NULL, *prep = NULL;        while(*s != '\0')        {            if(*s == *p || *p == '?')            {                s++;                p++;            }            else if(*p == '*')            {                prep = p;                pres = s;                p++;            }            else            {                if(prep == NULL)                    return false;                p = prep+1;                s = ++pres;            }        }        while(*p != '\0')        {            if(*p != '*')                return false;            p++;        }        return true;    }};


0 0