这个代码写的比较直觉,写的过程也出现好多细节问题,经过Clion debug调试才找到问题的。
所以写代码光有思路,不调试遇到一些麻烦问题也不好处理。
子结构1:
很好理解,字符相同,或者通配符是?,相互抵消一个字符
if(*p1 == *s1 || *p1 == '?'){
p1++;
s1++;
slen--;
plen--;
continue;
}
子结构2:
如果通配符不满足相等,也不是?,也不是*,那么没必要比下去了。返回false就好。
if(*p1 != '*'){
return false;
}
子结构3:
while(plen > 0 && *p1 == '*') {
plen--;
p1++;
if(plen == 0){
return true;
}
}
通配符剩下的字符全是*,把*清空之后,长度为0,没必要比下去了,直接返回true。因为*匹配任意字符。
子结构4:
if(slen == 0){
return false;
}
如果通配符不剩下的不全是*,但是字符串s已经清空了,没必要比较下去了,直接返回false。因为s找不到跟通配符匹配的字符了。
子结构5:
while(slen > 0 && plen > 0){
if(isMatch(s1,p1)){
return true;
}
s1++;
slen--;
}
双方互有子力,还可以比较。通配符刚刚有star过,那么通配符剩下的部分,跟s的任意子串匹配成功。就直接返回true。*可以匹配任意长度。
子结构6:
通配符刚刚有star过,但是通配符剩下的部分不能跟s的任意子串匹配,没必要比较了,直接返回false。
return false;
子结构7:
前面已经把通配符匹配过了,通配符不全是*,并且该匹配的字符也消掉了。双方剩下的子力字符都还存在,无法抵消。返回false
return slen == 0 && plen == 0;
class Solution {
public:
bool isMatch(const char *s, const char *p) {
int slen = strlen(s);
int plen = strlen(p);
const char *s1 = s;
const char *p1 = p;
while(slen > 0 && plen > 0){
if(*p1 == *s1 || *p1 == '?'){
p1++;
s1++;
slen--;
plen--;
continue;
}
if(*p1 != '*'){
return false;
}
while(plen > 0 && *p1 == '*') {
plen--;
p1++;
if(plen == 0){
return true;
}
}
if(slen == 0){
return false;
}
while(slen > 0 && plen > 0){
if(isMatch(s1,p1)){
return true;
}
s1++;
slen--;
}
return false;
}
while(plen > 0 && *p1 == '*'){
plen--;
p1++;
if(plen == 0){
return true;
}
}
return slen == 0 && plen == 0;
}
};



京公网安备 11010502036488号