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
class Solution {
public:
bool isMatch(string s, string p) {
int ls = s.size();
int lp = p.size();
int ps = 0;//s start
int pp = 0;
int star = -1;
int rs = -1;
while(ps < ls)
{
if(s[ps] == p[pp] || p[pp] == '?')
{
ps++;//s的当前下标
pp++;//p的当前下标
continue;
}
if(p[pp] == '*')
{
star = pp;//记录*的下标
rs = ps;//记录下s当前的下标
pp++;
continue;
}
if(star != -1)
{
pp = star + 1;//p中*后的一个下标
ps = rs + 1;
rs++;//s与p不匹配,s后移
continue;
}
return false;
}
while(pp < lp && p[pp] == '*') pp++;
return pp == lp;
}
};
- 二个指针i, j分别指向字符串、匹配公式。
-
如果匹配,直接2个指针一起前进。
-
如果匹配公式是*,在字符串中依次匹配即可。
下面是迭代程序,要熟悉这个思维:记录上一次开始比较的位置,如图:
每次遇到不满足条件的时候就回溯,每次遇到*时就更新回溯点。