[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

只能过小数据
 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         if (s == NULL && p == NULL)
 7             return true;
 8         else if (s == NULL || p == NULL)
 9             return false;
10             
11         if (*p == '?')
12         {
13             if (*s == '\0')
14                 return false;
15             else
16                 return isMatch(s + 1, p + 1);
17         }
18         else if (*p == '*')
19         {
20             while(*s != '\0')
21             {
22                 if (isMatch(s, p + 1))
23                     break;
24                 s++;
25             }
26             
27             if (*s != '\0')
28                 return true;
29             else
30                 return isMatch(s, p + 1);           
31         }
32         else
33         {
34             if (*s == *p)
35             {
36                 if (*s == '\0')
37                     return true;
38                 else
39                     return isMatch(s + 1, p + 1);
40             }
41             else
42                 return false;
43         }
44     }
45 };
posted @ 2012-11-27 10:23  chkkch  阅读(1377)  评论(0编辑  收藏  举报