I. Title Description
Implement wildcard pattern matching with support for '? ' 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
Two. Topic analysis
The main idea of the topic is to give a string of two strings s
and p
that the specified symbol ?
can match any single character and *
can match any sequence of characters (including the empty character sequence). Returns if two strings match exactly true
.
The difficulty of this problem mainly lies in the *
matching operation when it occurs. Similar to most practices on the web, the results are always timed out using recursive completion. Later use a few variables used to record the encountered in the subscript p
*
, each time you encounter one *
, the current string and the subscript is retained, s
p
and then s from the current subscript scan backward, if not match, then the subscript of S plus one, repeat scan.
Three. Sample code
#include <iostream>#include <string>using namespace STD;classSolution { Public:BOOLIsMatch (stringSstringP) {intS_size = S.size ();intP_size = P.size ();intS_index =0, P_index =0;intTemp_s_index =-1, Temp_p_index =-1; while(S_index < S_size) {if(P[p_index] = ='? '|| P[p_index] = = S[s_index]) {++p_index; ++s_index;Continue; }if(P[p_index] = =' * ') {temp_p_index = P_index; Temp_s_index = S_index; ++p_index;Continue; }if(Temp_p_index >=0) {The //string p may have multiple *, so as long as there is *, you need to update the current matching subscriptP_index = Temp_p_index +1; S_index = Temp_s_index +1;//The current coordinate s and p do not match, then the coordinates of s are added one on the original basis and continue to circulate++temp_s_index;Continue; }return false; } while(P[p_index] = =' * ') ++p_index;returnP_index = = P_size; }};
Four. Summary
The general recursive approach to this topic is preferred, but the biggest drawback of recursion is time-consuming. This problem can be solved by using dynamic programming, but it may not be able to achieve the above method
Leetcode notes: Wildcard Matching