The day before yesterday, we used recursive LTE, and yesterday we used dynamic LTE planning. Today we went on to use the greedy method. Repeat the question:
'? 'Match any character, '*' match any length string
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 function prototype should be:bool isMatch(const char *s, const char *p)
The idea is actually simpler. It is a bit like recursion. If two strings match from the beginning and do not match, false is returned. If the two strings match, 1 is added to both pointers. If P encounters *, then s ++ continues until p + 1 is matched. Of course, the position of P and S must be recorded for the next backtracking.
Use the image description:
In the worst case, the complexity is len_s * len_p, which is much smaller in most cases. The Code is as follows:
class Solution {public: bool isMatch(const char *s, const char *p) { const char *last_s = NULL; const char *last_p = NULL; while (‘\0‘ != *s || ‘*‘ == *p) { if (*s == *p || ‘?‘ == *p) { s++; p++; continue; } if (‘*‘ == *p) { while (‘*‘ == *p) { last_p = p; p++; } while (‘\0‘ != *s && (*s != *p && ‘?‘ != *p)) { s++; } last_s = s; continue; } if (last_p != NULL) { p = last_p; s = last_s+1; continue; } return false; } if (‘\0‘ == *p) { return true; } return false; }};
This time the AC is finally finished.
Initially, I intuitively felt that if there are N x in P, we need to save n locations for backtracking. In fact, we don't need to, as long as we need to ensure that the previous substring matches, the * matching below is not affected, that is, there are multiple matching schemes, but you only need to find one.
This solution is not very beautiful. First, the idea is not refreshing and it is easy to ignore some special cases. Wrong answer succeeded twice. Second, it is not like the first two solutions, it can solve the problem that both S and P have wildcards. Only P has wildcards, and the situation in S is complicated and not intuitive.