44. Wildcard Matching (String; Recursion)

來源:互聯網
上載者:User

標籤:

Implement wildcard pattern matching with support for ‘?‘ and ‘*‘.

‘?‘ Matches any single character.‘*‘ Matches any sequence of characters (including the empty sequence).不同於Regex中的*

*Regex的定義:

  • ‘.‘ 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", "*") → trueisMatch("aa", "a*") → trueisMatch("ab", "?*") → trueisMatch("aab", "c*a*b") → false

思路:當遇到*,可能匹配0, 1, 2, ...個字元=>帶回溯的遞迴

class Solution {public:    bool isMatch(string s, string p) {        star = false;        return recursiveCheck(s,p,0,0);    }        bool recursiveCheck(const string &s, const string &p, int sIndex, int pIndex){        if(sIndex >= s.length()){            while(p[pIndex] == ‘*‘ && pIndex < p.length()) pIndex++; //s has went to end, check if the rest of p are all *            return (pIndex==p.length());        }                if(pIndex >= p.length()){            return checkStar(s,p);        }                switch(p[pIndex]) //p: pattern,在p中才可能出現?, *        {         case ‘?‘:            return recursiveCheck(s, p, sIndex+1, pIndex+1);            break;        case ‘*‘: //如果當前為*, 那麼可認為之前的字元都匹配上了,並且將p移動到 * 結束後的第一個字元            star = true;  //p 每次指向的位置,要麼是最開始,要麼是 * 結束的第一個位置            starIndex = pIndex;            matchedIndex = sIndex-1;            while(p[pIndex] == ‘*‘&& pIndex < p.length()){pIndex++;} //忽略緊接在 *後面的*             if(pIndex==p.length()) return true;//最後一位是*            return recursiveCheck(s,p,sIndex,pIndex); //*匹配0個字元            break;        default:            if(s[sIndex] != p[pIndex]) return checkStar(s, p);            else return recursiveCheck(s, p, sIndex+1, pIndex+1);            break;         }    }        bool checkStar(const string &s, const string &p){        if(!star) return false;        else {            int pIndex = starIndex+1;            int sIndex = ++matchedIndex; //回溯,*d多匹配一個字元            return recursiveCheck(s, p, sIndex, pIndex);        }    }private:    int starIndex;    int matchedIndex;    bool star;};

 

44. Wildcard Matching (String; Recursion)

聯繫我們

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