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

Solution: ...

 1 class Solution {
 2 public:
 3     bool isMatch(const char *s, const char *p) {
 4         const char *sBackup = NULL, *pBackup = NULL;
 5         while (*s != '\0') {
 6             if (*p == '?' || *s == *p) {
 7                 s++;
 8                 p++;
 9             } else if (*p == '*') {
10                 while (*p == '*') p++;
11                 if (*p == '\0') return true;
12                 sBackup = s;
13                 pBackup = p;
14             } else {
15                 if (!sBackup) return false;
16                 s = ++sBackup;
17                 p = pBackup;
18             }
19         }
20         while (*p == '*') p++;
21         return *s == '\0' && *p == '\0';
22     }
23 };

 

 

posted @ 2014-04-24 04:32  beehard  阅读(139)  评论(0编辑  收藏  举报