面试题32:字符串的通配符匹配
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 int i = 0, j = 0; 5 int pstar = -1; 6 int sstar = -1; 7 while (s[i] != '\0') { 8 if (p[j] == '?' || s[i] == p[j]) { 9 i++; 10 j++; 11 } else if (p[j] == '*') { 12 pstar = j; 13 sstar = i; 14 j++; 15 } else { 16 if (pstar != -1) { 17 j = pstar + 1; 18 sstar++; 19 i = sstar; 20 } else { 21 return false; 22 } 23 } 24 } 25 26 while (p[j] == '*') { 27 j++; 28 } 29 return p[j] == '\0'; 30 31 } 32 };

浙公网安备 33010602011771号