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
题意:匹配两个字符串,?代表一个字符,*代表一个任意序列。
思路:贪心去做,重点是如果匹配"*",我们需要记录他的位置为start,和此时s串的位置tmp,然后对于p的下一位,我们是希望它能够匹配的,但是如果无法匹配的话,那么此时就需要用到我们标记的"*"的位置了,让"*"去多匹配一个字符,直到“*”的下一位能都匹配成功。
class Solution {
public:
bool isMatch(const char *s, const char *p) {
const char *start = NULL, *tmp = NULL;
while (*s != '\0') {
if (*s == *p || *p == '?') {
s++, p++;
continue;
}
if (*p == '*') {
start = p;
p++;
tmp = s;
continue;
}
if (start != NULL) {
p = start + 1;
s = tmp + 1;
tmp++;
continue;
}
return false;
}
while (*p == '*') p++;
return *p == '\0';
}
};
原文:http://blog.csdn.net/u011345136/article/details/44096509