LeetCode-Wildcard Matching

字符串匹配,

由于*可以匹配任意的一串字符,

必须遍历所有可能的匹配情况,所以这里用迭代比递归要更好一点,

遇到*之后,假定*匹配0个字符,一直到匹配整个s字符,遍历判断是否可以匹配成功;

用指针prep记录*后面一个非*字符,用pres来记录遍历的起始点;

 1 class Solution {
 2 public:
 3     bool isMatch(const char *s, const char *p) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         const char *pres = NULL, *prep = NULL;
 7         while (*s) {
 8             if (*p == '?' || *s == *p) {
 9                 ++s;
10                 ++p;
11             }
12             else {
13                 if (*p == '*') {
14                     while (*p == '*')
15                         ++p;
16                     if (*p == '') 
17                         return true;
18                     pres = s;
19                     prep = p;
20                 }
21                 else {
22                     if (pres) {
23                         s = ++pres;
24                         p = prep;
25                     }
26                     else {
27                         return false;
28                     }
29                 }
30             }
31         }
32         while (*p == '*')
33             ++p;
34         return (*s == '' && *p == '');
35     }
36 };
原文地址:https://www.cnblogs.com/chasuner/p/wildmatch.html