根据题设 引入两个索引,代表子部分匹配
跟判断两个二叉树是否是镜像
还有一个问题是啥来着。有想通指出。
我的代码:暴力递归方法,
还可以改成动态规划方法;
public static void main(String[] args) {
String a = "aabbc";
String p = "aabb.d*e*";
String aa = "ab";
String pp = ".*";
String aaa = "aaba";
String ppp = "ab*a*c*a";
System.out.println(isMatch(aaa, ppp));
}
public static boolean isMatch(String s, String p) {
int[] freq = new int [s.length()];
char pre = '0';
for(int i = s.length()-1; i>=0; i--){
freq[i] = 1;
if(s.charAt(i)== pre){
freq[i] ++;
}
pre = s.charAt(i);
}
return process(s.toCharArray(), 0, p.toCharArray(), 0 , freq);
}
public static boolean process(char[] s, int index1, char[] p, int index2, int[] freq){
/**当pattern没有了,s还有没匹配的时候,*/
if(index2 < p.length && p[index2] == '*') return false;
if(index1 == s.length && index2== p.length) return true;
if(index2 == p.length && index1 < s.length){
return false;
}
if(index1 == s.length && index2 < p.length){
while(index2 +1 < p.length &&p[index2 +1] == '*'){
index2+=2;
}
if(index2==p.length) return true;
else return false;
}
boolean res = false;
if( index2 + 1 < p.length && p[index2+1]!= '*'){
if(p[index2] !='.' && s[index1] != p[index2]){
return false;
}
res = process(s, index1+1, p,index2+1, freq);
}
else if( index2 +1 < p.length && p[index2 +1] == '*'){
/** 星号可以不匹配任何字符,也可以任意数量,只要字符相同*/
if(p[index2]!='.' && p[index2] !=s[index1]){
res = process(s, index1, p, index2+2, freq);
return res;
}
else if(p[index2]!='.' && p[index2] ==s[index1]) {
/** 潜台词: index1 和 index2 不命中**/
for(int f = 0; f<=freq[index1];f++ ){
res = res || process(s, index1 +f, p, index2+2, freq);
}
return res;
}
else if(p[index2]=='.'){
for(int l = index1; l<= s.length; l ++){
res = res|| process(s, l, p ,index2 +2, freq);
}
return res;
}
}
else if(p[index2] == s[index1] || p[index2] == '.'){
res = process(s, index1+1, p, index2 +1, freq);
}
return res;
}