Leetcode 44: 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 public class Solution {
 2     public bool IsMatch(string s, string p) {
 3         if (s == null || p == null) return s == null && p == null;
 4         
 5         int i = 0, j = 0, star = -1, match = -1;
 6         
 7         while (i < s.Length)
 8         {
 9             if (j < p.Length && (s[i] == p[j] || p[j] == '?'))
10             {
11                 i++;
12                 j++;
13             }
14             else if (j < p.Length && p[j] == '*')
15             {
16                 star = j;
17                 match = i;
18                 j++;
19             }
20             else if (star != -1)
21             {
22                 match++;
23                 i = match;
24                 j = star + 1;
25             }
26             else
27             {
28                 return false;
29             }
30         }
31         
32         while (j < p.Length)
33         {
34             if (p[j++] != '*') return false;
35         }
36         
37         return true;
38     }
39 }

 

posted @ 2018-01-31 12:08  逸朵  阅读(93)  评论(0编辑  收藏  举报