The leetcode question is quite interesting. It implements wildcards ,'? 'Match any character, '*' match any length string. Try it at night. The question is as follows:
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
The direct idea is very simple. If two strings match from the beginning, the system returns false if they do not match. If they match, the two pointers are added with 1 to match the sub-string. Therefore, we naturally want to implement them using recursion.
The complexity is that * matches strings of any length. Therefore, * can be used to determine the substring after * recursive ismatch. The implementation is as follows:
class Solution {public: bool isMatch(const char *s, const char *p) { if (‘\0‘ == *s && ‘\0‘ == *p) { return true; } if (‘*‘ == *s) { return asteriskMatch(s, p); } if (‘*‘ == *p) { return asteriskMatch(p, s); } if (*s == *p || ‘?‘ == *s || ‘?‘ == *p) { s++; p++; return isMatch(s, p); } else { return false; } }private: bool asteriskMatch(const char *asterisk, const char *p) { asterisk++; if (‘*‘ == *asterisk) { return asteriskMatch(asterisk, p); } while (*p != ‘\0‘) { if (isMatch(asterisk, p)) { return true; } p++; } if (‘\0‘ == *asterisk && ‘\0‘ == *p) { return true; } return false; }};
In this way, the code is refreshing, but * The Judgment efficiency is obviously not high, and the submission is indeed time limit exceeded. The failure case is:
Last executed input: |
"Zookeeper ", "** AA ** Ba ** A * BB ** AA * AB ** A * aaaaaa ** A * AAAA ** bbabb * B * * aaaaaaaaa * A ******** ba * BBB ***** A * ba * BB ** a * B * BB" |
We should try using dynamic planning or greedy methods, but we always think that Recursive Implementation is more elegant. In addition, it seems that many people in discuss still use DP. It's not good. It's too sleepy. Let's change it tomorrow.