leetcode之萬用字元

來源:互聯網
上載者:User

標籤:wildcard matching   regular expression m   leetcode   wildcard   pattern matching   

Wildcard Matching

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* sBegin = NULL,*pBegin = NULL;    while(*s)    {    if(*s == *p || *p == '?')    {    ++s;    ++p;    }    else if(*p == '*')    {    pBegin = p;//記錄萬用字元的位置    sBegin = s;    ++p;    }    else if(pBegin != NULL)    {    p = pBegin + 1;//重萬用字元的下一個字元開始    ++sBegin;//每次多統配一個    s = sBegin;    }    else return false;    }    while(*p == '*')++p;    return (*p == '\0');    }};

Regular Expression Matching 

Implement regular expression matching with support for ‘.‘ and ‘*‘.

‘.‘ Matches any single character.‘*‘ Matches zero or more of the preceding element.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", "a*") → trueisMatch("aa", ".*") → trueisMatch("ab", ".*") → trueisMatch("aab", "c*a*b") → true
思路:本題和上面不同之處在於,此時的萬用字元‘*‘是代表0到多個前一個字元,而不是任一個字元。所以,當下一個字元是‘*‘時,如果當前字元相等,則反覆跳過當前字元去匹配‘*‘後面的字元,如果不相等,則直接匹配‘*‘後面的字元。
class Solution {public:    bool isMatch(const char *s, const char *p) {    if(*p == '\0')return *s == '\0';    if(*(p+1) != '*')    {    if(*s != '\0' && (*s == *p || *p == '.'))return isMatch(s+1,p+1);    }    else     {    //s向後移動0、1、2……分別和p+2進行匹配    while(*s != '\0' && (*s == *p || *p == '.'))    {    if(isMatch(s,p+2))return true;    ++s;    }    return isMatch(s,p+2);    }    return false;    }};



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.