[leetCode]剑指 Offer 19. 正则表达式匹配
递归解法
如果匹配的下一个字符不是 ‘’则继续匹配下一个字符
如果匹配的下一个字符是‘’则有多种选择:
matchCore(s,p, sIdx + 1, pIdx + 2)
跳过“*”,匹配下一个字符matchCore(s,p, sIdx + 1, pIdx)
不跳过‘*’,继续匹配matchCore(s,p, sIdx, pIdx + 2)
忽略 *
class Solution {
public boolean isMatch(String s, String p) {
if(s == null || p == null)
return false;
return matchCore(s, p, 0, 0);
}
private boolean matchCore(String s, String p, int sIdx, int pIdx){
if(sIdx == s.length() && pIdx == p.length())//匹配完成返回真
return true;
if(sIdx != s.length() && pIdx == p.length())//匹配失败
return false;
if(pIdx + 1 != p.length() && p.charAt(pIdx + 1) == '*'){//如果pattern中下一个是‘*’
if(pIdx < p.length() && sIdx < s.length() && (p.charAt(pIdx) == s.charAt(sIdx)
|| (p.charAt(pIdx) == '.' && sIdx != s.length()))){
return matchCore(s,p, sIdx + 1, pIdx + 2) ||
matchCore(s,p, sIdx + 1, pIdx) ||
matchCore(s,p, sIdx, pIdx + 2);
}else{
return matchCore(s,p, sIdx, pIdx + 2);
}
}
if(pIdx < p.length() && sIdx < s.length() && (p.charAt(pIdx) == s.charAt(sIdx)
|| (p.charAt(pIdx) == '.' && sIdx != s.length())))
return matchCore(s,p, sIdx + 1, pIdx + 1);
return false;
}
}