標籤:
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)