题目链接: 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 si = 0, pi = 0, oldsi = -1, oldpi=-1; while(si < s.size()) { if(s[si] == p[pi] || p[pi]=='?') si++, pi++; else if(pi < p.size() && p[pi] =='*') { oldsi = si + 1; oldpi = pi; pi++; } else if(oldpi!= -1 && s[si] != p[pi]) { si = oldsi; pi = oldpi; } else return false; } while(pi < p.size() && p[pi]=='*') pi++; return pi == p.size(); } };参考: https://leetcode.com/discuss/49254/fastest-non-dp-solution-with-o-1-space