题目链接: https://leetcode.com/problems/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
思路: 有两种特殊字符, '?'代表匹配一个任意字符, 这个比较好处理. '*'匹配任意多个字符, 这个需要考虑匹配多个字符. 因此我们可以记下最后出现'*'的位置, 这样当后面位置不匹配的时候再回到这里将不匹配的字符用'*'来匹配. 这样最后再判断是否p指针停留的位置到最后都是*, 如果是的话则可以匹配, 否则不可以匹配. 一个例子如: s = "aa", p = "aa****".
代码如下:
class Solution {
public:
bool isMatch(string s, string p) {
int preS=-1, preP=-1, i=0, j=0, len1=s.size(), len2=p.size();
while(i < len1)
{
if(s[i]==p[j] || p[j]=='?') i++, j++;
else if(p[j]=='*') preS=i+1, preP = j++;
else if(preP==-1) return false;
else i = preS, j = preP;
}
while(p[j]=='*') j++;
return i==len1&&j==len2;
}
};
参考: https://leetcode.com/discuss/49254/fastest-non-dp-solution-with-o-1-space