[LeetCode][JavaScript]Wildcard Matching

Wildcard Matching

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") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false

https://leetcode.com/problems/wildcard-matching/


一开始用歪门邪道做果然挂了,合并所有的*,用.*代替*,用.代替?,加开始符^和结束符$,直接用正则表达式去匹配,妥妥的TLE。

贪心+回溯

回溯:当遇到*的时候,p指针往后走一步,如果还是*则继续走,直到不是*为止,这时s不走与p匹配(*匹配的是空)。

如果不匹配,回溯回去,s指针走一步与当前的p匹配(*匹配了一个字符),以此类推。

贪心:当*之后的一个字符与s当前的字符匹配的时候,就认为这之前的字符都匹配好了,之后遇到*不需要回溯到已经匹配好的*了(只需要回溯到最近的*)。

基于这点我们需要记下最近的*的位置,从这里开始回溯就好了。

 1 /**
 2  * @param {string} s
 3  * @param {string} p
 4  * @return {boolean}
 5  */
 6 var isMatch = function(s, p) {
 7     var starS = null, starP = null;
 8     var i = 0, j = 0;
 9     while(s[i]){
10         if(s[i] === p [j] || p[j] === '?'){
11             i++; j++;
12             continue;
13         }
14         if(p[j] === '*'){
15             while(p[j + 1] && p[j + 1] === '*'){
16                 j++;
17             }
18             starS = i; starP = j; j++;
19             continue;
20         }
21         if(starS !== null){
22             i = starS + 1; j = starP + 1; starS++;
23             continue;
24         }
25         return false;
26     }
27     while(p[j] === '*'){
28         j++;
29     }
30 
31     return !p[j];
32 };
原文地址:https://www.cnblogs.com/Liok3187/p/4657924.html