leetcode: Wildcard Matching
http://oj.leetcode.com/problems/wildcard-matching/
Implement wildcard pattern matching with support for '?' and '*'.
'?' Matches any single character. The matching should cover the entire input string (not partial). The function prototype should be: Some examples: |
思路:
参考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 != '\0') { 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 (('\0' == *s) && ('\0' == *p)); 40 } 41 };