leetcode: Wildcard Matching

http://oj.leetcode.com/problems/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

思路

参考Regular Expression Matching的思路,'*'分别尝试匹配0个或多个字符。每次遇到'*'号时,一个和n个没有区别,我们保留现场s的位置和最后一个*号位置,在需要调整的时候把已经保存的值取出来就可以了。

 1 class Solution {
 2 public:
 3     bool isMatch(const char *s, const char *p) {
 4         bool star = false;
 5         const char *saved_s = NULL, *saved_p = NULL;
 6         
 7         while (*s != '') {
 8             if (*p != '*') {
 9                 if ((*s == *p) || ('?' == *p)) {
10                     ++s;
11                     ++p;
12                 }
13                 else {
14                     if (star) {
15                         s = ++saved_s;
16                         p = saved_p + 1;
17                     }
18                     else {
19                         return false;
20                     }
21                 }
22             }
23             else {
24                 star = true;
25                 
26                 while ('*' == *p) {
27                     ++p;
28                 }
29                 
30                 saved_s = s;
31                 saved_p = p - 1;
32             }
33         }
34         
35         while ('*' == *p) {
36             ++p;
37         }
38         
39         return (('' == *s) && ('' == *p));
40     }
41 };
原文地址:https://www.cnblogs.com/panda_lin/p/wildcard_matching.html