模糊匹配算法
liru:
输入
asdfgh
a?d
输出 3
package com.qst.Tesst;
import java.util.Scanner;
/*
*
* 模糊匹配算法
*
* */
public class Test10 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char[] str = scanner.nextLine().toCharArray();
char[] sub = scanner.nextLine().toCharArray();
if (str.length<sub.length){
//System.out.println(-1);
return;
}
int count =robot(str,sub,0,0);
System.out.println(count);
}
private static int robot(char[] str, char[] sub, int strbeg, int subbeg) {
if (strbeg==str.length||subbeg>sub.length){
return -1;
}
while (subbeg<sub.length){
if (str[strbeg]==sub[subbeg]){
++strbeg;
++subbeg;
}else {
if (sub[subbeg]=='?'){
int a = robot(str,sub,strbeg+1,subbeg+1);
int b = robot(str,sub,strbeg+2,subbeg+1);
int c = robot(str,sub,strbeg+3,subbeg+1);
if (a==-1){
a =Integer.MAX_VALUE;
}
if (b==-1){
a =Integer.MAX_VALUE;
}
if (a==-1){
a =Integer.MAX_VALUE;
}
int ans = Math.min(c,Math.min(a,b));
if (ans ==Integer.MAX_VALUE){
return -1;
}else{
return ans;
}
}else{
return -1;
}
}
}
return strbeg;
}
}