Wildcard Matching
Implement wildcard pattern matching with the 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", "? *") →truei Smatch ("AaB", "C*a*b") →false
https://leetcode.com/problems/wildcard-matching/
The beginning with astray do really hang up, merge all the *, with. * Instead of *, use. Instead, add the start character ^ and Terminator $, and use regular expressions to match the proper tle.
Greedy + backtracking
Backtracking: When encountering A *, the p pointer moves back one step, if still * then continue to walk, until not, then s does not go with P match (* match is empty).
If it doesn't match, go back, the s pointer goes one step closer to the current P (* matches a character), and so on.
Greedy: When a character after * matches the current character of S, it is assumed that the previous characters are matched, and then encountered * does not need to go back to the already matched * (only the nearest * is required).
Based on this we need to write down the location of the nearest *, starting from here to backtrack.
1 /**2 * @param {string} s3 * @param {string} p4 * @return {Boolean}5 */6 varIsMatch =function(S, p) {7 varStarS =NULL, Starp =NULL;8 vari = 0, j = 0;9 while(S[i]) {Ten if(S[i] = = = P [j] | | p[j] = = = '? '){ Onei++; J + +; A Continue; - } - if(P[j] = = = ' * '){ the while(P[j + 1] && p[j + 1] = = = ' * '){ -J + +; - } -StarS = i; Starp = j; J + +; + Continue; - } + if(StarS!==NULL){ Ai = StarS + 1; j = starp + 1; stars++; at Continue; - } - return false; - } - while(P[j] = = = ' * '){ -J + +; in } - to return!P[j]; +};
[Leetcode] [JavaScript] Wildcard Matching