这里只讨论通配符 ‘ * ’ 和 ‘ ?‘ 的情况?
1. 当前字符是 “ * ” 的时候,表示可以匹配 0 至任意个字符
2. 当前字符是 “ ?“ 的时候,表示可以匹配 0 或者 1 个字符
3. 解题思路就是当遇到通配符的时候。利用回溯的思想解决
代码如下:
public class Pattern {
private boolean matched = false;
private char[] pattern;
private int pLen;
public Pattern(char[] pattern, int pLen){
this.pattern = pattern;
this.pLen = pLen;
}
// 匹配函数
public boolean match(char[] text, int tLen){
matched = false;
rematch(0, 0, text, tLen);
return matched;
}
// 匹配的过程
public void rematch(int ti, int pj, char[] text, int tLen){
if(matched) return;
if(pj == pLen){
if(ti == tLen){
matched = true;
return;
}
}
// 当前字符为 ’*‘
if(pattern[pj] == '*'){
for(int k = 0; k <= tLen - ti; k++){
rematch(ti + k, pj + 1, text, tLen);
}
}
// 当前字符为 ’?‘
else if(pattern[pj] == '?'){
rematch(ti, pj + 1, text, tLen);
rematch(ti + 1, pj + 1, text, tLen);
}
// 当前字符匹配成功
else if(ti < tLen && pattern[pj] == text[ti]){
rematch(ti + 1, pj + 1, text, tLen);
}
}
来源:oschina
链接:https://my.oschina.net/happywe/blog/3165029