java代码
class Solution {
public boolean isMatch(String str, String pattern) {
if (str == null || pattern == null) {
return true;
}
int strIndex = 0;
int patternIndex = 0;
return matchCore(str.toCharArray(), strIndex, pattern.toCharArray(), patternIndex);
}
public boolean matchCore(char[] str, int strIndex, char[] pattern, int patternIndex) {
//如果字符串与模式串同时访问完毕
if(strIndex==str.length && patternIndex==pattern.length){
return true;
}
//如果模式串访问完毕而字符串未访问完
if(pattern.length==patternIndex && str.length!=strIndex){
return false;
}
//如果模式串第二个字符是*那么
if(patternIndex+1<pattern.length && pattern[patternIndex+1]=='*'){
if(strIndex<str.length && matchChar(str[strIndex],pattern[patternIndex])){
// System.out.println("1");
return matchCore(str,strIndex+1,pattern,patternIndex) ||
matchCore(str,strIndex+1,pattern,patternIndex+2) ||
matchCore(str,strIndex,pattern,patternIndex+2);
}else {
// System.out.println("2");
return matchCore(str,strIndex,pattern,patternIndex+2);
}
}
if(strIndex<str.length && matchChar(str[strIndex],pattern[patternIndex])){
// System.out.println("3");
return matchCore(str,strIndex+1,pattern,patternIndex+1);
}
if(strIndex<str.length && !matchChar(str[strIndex],pattern[patternIndex])){
// System.out.println("4");
return false;
}
// System.out.println("5");
return false;
}
public boolean matchChar(char ch1,char ch2){
if(ch1==ch2||ch2=='.'){
return true;
}
return false;
}
}