[Leetcode] Wildcard Matching

来源:互联网 发布:python正则表达式替换 编辑:程序博客网 时间:2024/06/06 11:44

题目:

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


思路:如果没有*的干扰,那么顺序向后比较即可。在*存在时,需要列举*对应多个字符的情况。标记p字符串*后面的第一个非*字符,以及s字符串的当前字符,设为b_s和b_p。当后面发生不匹配时,回溯到这个状态,用b_p去匹配b_s + 1,即,用*去匹配多一个字符。例如abc  *c,第一次记录b_s为a,b_p为c,发生不匹配时,回溯,用c去匹配b(这时*去匹配a);再次发生不匹配,回溯,用c去匹配c(这时*去匹配a和b),不断扩大*的作用范围,直到匹配成功,或*匹配完s后面的所有字符而p后面还有非*非?字符。


class Solution {public:    bool isMatch(const char *s, const char *p) {        const char* backtrack_s = nullptr;        const char* backtrack_p = nullptr;        while (*s != '\0') {            if (*s == *p || *p == '?') {                s++;                p++;            } else if (*p == '*') {                while (*p == '*') p++;   //move forward until meet the first non-star character                if (*p == '\0') return true;   //no character left after '*'                // record the position of current s                // and the first non-star character of p after a sequential '*'                backtrack_s = s;                backtrack_p = p;            } else {   //*s != *p && *p != '*'                if (backtrack_s == nullptr || backtrack_p == nullptr) return false;                s = backtrack_s++;   //let '*' to match one more character                p = backtrack_p;            }        }        while (*p == '*') p++;        return *p == '\0';    }};


总结:复杂度为O(nm),最坏情况可能需要不断回溯。

0 0
原创粉丝点击