WildcardMatchingImplementwildcardpatternmatchingwithsupportfor & #160; & #39 ;? & #39; & #160; and & #160; & #39; * & #39;. & #39 ;? & #39; Matchesanysinglecharacter. & #39 ;*
Wildcard Matching
Implement wildcard pattern matching with support'?'
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
Idea: This question is a normal wildcard match. you can use loops or recursion. When a loop is used, the location of '*' is recorded every time. in this way, when the matching fails, the matching at this location is returned.
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; // records the position of the wildcard sBegin = s; + + p;} else if (pBegin! = NULL) {p = pBegin + 1; // the next character starting with a duplicate wildcard + + sBegin; // One s = sBegin;} else return false ;} while (* p = '*') + + p; return (* p = '\ 0 ');}};
Regular Expression Matching
Implement regular expression matching with support'.'
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
Train of Thought: This question differs from the above in that the wildcard '*' at this time represents 0 to multiple first characters, not any one character. Therefore, when the next character is '*', if the current character is equal, the current character is skipped repeatedly to match the character after '*'. if not, match the characters following.
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 Move 0, 1, 2 ...... Match with p + 2 respectively while (* s! = '\ 0' & (* s = * p | * p = '. ') {if (isMatch (s, p + 2) return true; ++ s;} return isMatch (s, p + 2);} return false ;}};