zoukankan      html  css  js  c++  java
  • [LeetCode]wildcard matching通配符实现之递归

    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") → 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

    直接的思路很简单,两个字符串从头开始匹配,不匹配直接返回false,匹配,则两个指针都加1,匹配子字符串,所以自然而然就想用递归来实现。
    复杂一点的是*号,匹配任意长度的字符串,所以*的判断也可以循环的递归isMatch判断*后的子字符串。实现如下:
    class Solution {
    public:
        bool isMatch(const char *s, const char *p) {
            if ('' == *s && '' == *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 != '')
            {
                if (isMatch(asterisk, p))
                {
                    return true;
                }
                p++;
            }
            if ('' == *asterisk && '' == *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,不行了,太困了,明天再改吧

  • 相关阅读:
    区块链服务平台设计
    Fabric 架构与设计
    ELSE 技术周刊(2017.12.25期)
    ELSE 技术周刊(2017.12.25期)
    ELSE 技术周刊(2017.12.25期)
    UDT的Sender和Receiver
    UDT的Sender和Receiver
    UDT的Sender和Receiver
    UDT的Sender和Receiver
    JavaScript 后台获取数据
  • 原文地址:https://www.cnblogs.com/yezhangxiang/p/3915900.html
Copyright © 2011-2022 走看看