44. Wildcard Matching
来源:互联网 发布:python 爬虫 股票数据 编辑:程序博客网 时间:2024/06/06 00:12
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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "*") → trueisMatch("aa", "a*") → trueisMatch("ab", "?*") → trueisMatch("aab", "c*a*b") → false
思路:
p : abcd*def*ass*sss。这样的匹配实际上就是要查找字符串s中是否有如下按照一定顺序的序列:abcd、def、ass和sss。只有这四个字符串按照顺序出现,那么就匹配成功。这个很关键。
如果我们匹配到abcd*def*ass时,下一个字符是,然后把这个继续展开,那么前面的这几个还需要进一步展开吗?当然不需要了。因为他们的目的已经实现了,就是已经找到了前几个可以匹配的字符。现在需要的就是在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; }}
阅读全文