[LeetCode]wildcard matching萬用字元實現之貪進法

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   ar   2014   cti   

前天用遞迴LTE,昨天用動態規劃LTE,今天接著搞,改用貪進法。題目再放一次:

‘?‘匹配任一字元,‘*‘匹配任意長度字串

Some examples:isMatch("aa","a") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "*") → trueisMatch("aa", "a*") → trueisMatch("ab", "?*") → trueisMatch("aab", "c*a*b") → false
The function prototype should be:bool isMatch(const char *s, const char *p)
思路其實更簡單,和遞迴的有點像,兩個字串從頭開始匹配,不匹配直接返回false,匹配,則兩個指標都加1,若p遇到*,則s++一直到匹配到p+1,當然要記錄此時p和s的位置,以便下次回溯.
還是用圖片說明吧:


用該方法,最差情況下複雜度為len_s*len_p,絕大情況下其實小很多.具體代碼如下:
class Solution {public:    bool isMatch(const char *s, const char *p) {        const char *last_s = NULL;        const char *last_p = NULL;        while (‘\0‘ != *s || ‘*‘ == *p)        {            if (*s == *p || ‘?‘ == *p)            {                s++;                p++;                continue;            }            if (‘*‘ == *p)            {                while (‘*‘ == *p)                {                    last_p = p;                    p++;                }                while (‘\0‘ != *s && (*s != *p && ‘?‘ != *p))                {                    s++;                }                last_s = s;                continue;            }            if (last_p != NULL)            {                p = last_p;                s = last_s+1;                continue;            }            return false;        }        if (‘\0‘ == *p)        {            return true;        }        return false;    }};

這次終於AC了.

最初的時候直觀的感覺如果p中有n個*就要儲存多個n個位置以回溯,其實不用,只要保證前面的子串匹配了,後面的*匹配不受影響,就是有多種匹配方案,但是只要找到一種就可以了.

這個解決方案感覺不是很美,一是思路不清爽,很容易忽略一些特殊情況,Wrong Answer了兩次才成功;二是不像前兩種,能解決s和p都帶有萬用字元的情況,只能做只有p中有萬用字元,s中也有的情況感覺分析起來很複雜,不直觀.



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.