0
点赞
收藏
分享

微信扫一扫

44. 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 : abcddefasssss。这样的匹配实际上就是要查找字符串s中是否有如下按照一定顺序的序列:abcd、def、ass和sss。只有这四个字符串按照顺序出现,那么就匹配成功。这个很关键。
如果我们匹配到abcd
defass时,下一个字符是,然后把这个继续展开,那么前面的这几个还需要进一步展开吗?当然不需要了。因为他们的目的已经实现了,就是已经找到了前几个可以匹配的字符。现在需要的就是在sIndex之后的字符串s中,找到是否有sss这个字符串,而这个匹配的工作,由最后这个已经完全可以胜任了。那么有没有可能是后面的字符串中没有sss,而在前面出现呢?即使有可能也没用,因为还有一个重要的前提是,有序。
这样就可以使用迭代法。每次遇到不满足条件的时候就回溯,每次遇到
时就更新回溯点。

class Solution {
public boolean isMatch(String s, String p) {
char[] chars = s.toCharArray();
char[] charp = p.toCharArray();

int ss = -1, pp = -1;
int sIndex = 0, pIndex = 0;

while (sIndex < chars.length) {
if (pIndex == charp.length) {//false,回溯
if(pp == -1)
return false;

pIndex = pp + 1;
sIndex = ss++;
} else if (charp[pIndex] == '?' || chars[sIndex] == charp[pIndex]) {//相同
pIndex++;
sIndex++;
} else if (charp[pIndex] == '*') {
pp = pIndex;
ss = sIndex;
pIndex = pp+1;
} else {
if (pp == -1)
return false;
pIndex = pp + 1;
sIndex = ss++;
}
}

while (pIndex < charp.length) {
if(charp[pIndex] != '*')
break;
pIndex++;
}

return pIndex == charp.length;
}
}

class Solution {
public boolean isMatch(String s, String p) {
char[] ss = s.toCharArray();
char[] ps = p.toCharArray();
int m=ps.length, n=ss.length;
int idx1=0, idx2=0, start=-1;
while (idx2<n){
if (idx1<m && (ps[idx1]==ss[idx2]||ps[idx1]=='?')){
idx1 ++;
idx2 ++;
}else if (idx1<m && ps[idx1]=='*'){
start = idx1;
idx1 ++;
}else if (start!=-1){
idx2 = idx2-(idx1-start-1)+1;
idx1 = start+1;
}else return false;
}
while (idx1<m && ps[idx1]=='*') idx1++;
return idx1==m? true:false;
}
}


举报

相关推荐

0 条评论