首页 > 代码库 > [LeetCode]wildcard matching通配符实现TLE

[LeetCode]wildcard matching通配符实现TLE

leetcode这道题还挺有意思的,实现通配符,‘?‘匹配任意字符,‘*‘匹配任意长度字符串,晚上尝试了一下,题目如下:


 

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

直接的思路很简单,两个字符串从头开始匹配,不匹配直接返回false,匹配,则两个指针都加1,匹配子字符串,所以自然而然就想用递归来实现。
复杂一点的是*号,匹配任意长度的字符串,所以*的判断也可以循环的递归isMatch判断*后的子字符串。实现如下:
class Solution {public:    bool isMatch(const char *s, const char *p) {        if (\0 == *s && \0 == *p)        {            return true;        }        if (* == *s)        {            return asteriskMatch(s, p);        }        if (* == *p)        {            return asteriskMatch(p, s);        }        if (*s == *p || ? == *s || ? == *p)        {            s++;            p++;            return isMatch(s, p);        }        else        {            return false;        }    }private:    bool asteriskMatch(const char *asterisk, const char *p)    {        asterisk++;        if (* == *asterisk)        {            return asteriskMatch(asterisk, p);        }        while (*p != \0)        {            if (isMatch(asterisk, p))            {                return true;            }            p++;        }        if (\0 == *asterisk && \0 == *p)        {            return true;        }        return false;    }};

这样实现代码比较清爽,但是*的判断效率明显不高,提交,果然Time Limit Exceeded.没通过的用例是:

Last executed input:"abbabaaabbabbaababbabbbbbabbbabbbabaaaaababababbbabababaabbababaabbbbbbaaaabababbbaabbbbaabbbbababababbaabbaababaabbbababababbbbaaabbbbbabaaaabbababbbbaababaabbababbbbbababbbabaaaaaaaabbbbbaabaaababaaaabb", "**aa*****ba*a*bb**aa*ab****a*aaaaaa***a*aaaa**bbabb*b*b**aaaaaaaaa*a********ba*bbb***a*ba*bb*bb**a*b*bb"

应该改用动态规划或者贪心法试试,不过总是觉得用递归实现比较优雅,而且看Discuss里很多人用DP也还是TLE,不行了,太困了,明天再改吧