[Leetcode] 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

碉堡了,可以用动规,但是如果存储n*m的表的话会爆内存,可以用2*m的表存,也可以回溯法,存储star的位置,后面不匹配的话就回退到star的位置重新匹配。

 1 class Solution {
 2 //if strlen is used, then it will be TLE
 3 //iteration based solution
 4 public:
 5     bool isMatch(const char *s, const char *p) {
 6         bool star = false;
 7         const char *starPos = NULL;
 8         const char *savePos = NULL;
 9         while (*s != '') {
10             if (*p == '?') {
11                 ++p; ++s;
12             } else if (*p == '*') {
13                 while (*p == '*') ++p;
14                 star = true;
15                 starPos = p;
16                 savePos = s;
17             } else {
18                 if (*p == *s) {
19                     ++p; ++s;
20                 } else {
21                     if (star) {
22                         s = ++savePos;
23                         p = starPos;
24                     } else {
25                         return false;
26                     }
27                 }
28             }
29         }
30         while (*p == '*') ++p;
31         return (*s == '') && (*p == '');
32     }
33 };
原文地址:https://www.cnblogs.com/easonliu/p/3694775.html