思路一:
利用递归,当遇到*,进行深搜的递归。
/*boolean isMatch=false;
public boolean isMatch(String s, String p) {
dfs(s,p);
return isMatch;
}
public void dfs(String s,String p){
if(s.length()==0&&p.length()==0){
isMatch=true;
return;
}
if(s.length()==0||p.length()==0)return;
if(p.charAt(0)!='*'&&p.charAt(0)!='?'){
if(p.charAt(0)!=s.charAt(0))return;
else dfs(s.substring(1),p.substring(1));
}
else if(p.charAt(0)=='?'){
dfs(s.substring(1),p.substring(1));
}else{
for(int i=0;i<s.length()+1;i++){
dfs(s.substring(i),p.substring(1));
}
}
}*/
结果超时,需要转化成动态规划
思路二:
建立二维矩阵match[][],match[i][j]表示p(0,i)与s[0,j]是否匹配,按照从上先下从左至右的顺序构建矩阵,最后match[row-1][column-1]表示能否匹配
public boolean isMatch(String s, String p){
if(s.length()==0&&p.length()==0)return true;
if(p.length()==0)return false;
if(s.length()==0){
for(int i=0;i<p.length();i++){
if(p.charAt(i)!='*')return false;
}
return true;
}
boolean[][]match=new boolean[p.length()][s.length()];
int num=0;
if(p.charAt(0)!='*'&&p.charAt(0)!='?'){
match[0][0]=(p.charAt(0)==s.charAt(0));
num++;
}
else if(p.charAt(0)=='?'){
match[0][0]=true;
num++;
for(int i=1;i<s.length();i++){
match[0][i]=false;
}
}else{
for(int i=0;i<s.length();i++){
match[0][i]=true;
}
}
for(int i=1;i<p.length();i++){
if(num==0){
if(p.charAt(i)!='*'&&p.charAt(i)!='?'){
match[i][0]=(p.charAt(i)==s.charAt(0));
num++;
}
else if(p.charAt(i)=='?'){
match[i][0]=true;
num++;
}else{
match[i][0]=true;
}
}
else if(p.charAt(i)=='*'){
match[i][0]=match[i-1][0];
}else{
match[i][0]=false;
}
}
for(int i=1;i<p.length();i++){
for(int j=1;j<s.length();j++){
if(p.charAt(i)!='*'&&p.charAt(i)!='?'){
match[i][j]=match[i-1][j-1]&&(p.charAt(i)==s.charAt(j));
}
else if(p.charAt(i)=='?'){
match[i][j]=match[i-1][j-1];
}else{
match[i][j]=false;
for(int k=0;k<=j;k++){
if(match[i-1][k]){
match[i][j]=true;
break;
}
}
}
}
}
return match[p.length()-1][s.length()-1];
}