描述
问题描述:在计算机中,通配符一种特殊语法,广泛应用于文件搜索、数据库、正则表达式等领域。现要求各位实现字符串通配符的算法。
要求:
实现如下2个通配符:
*:匹配0个或以上的字符(注:能被*和?匹配的字符仅由英文字母和数字0到9组成,下同)
?:匹配1个字符
注意:匹配时不区分大小写。
/**
*
* 这种写法会有一个用例超时,暴力处理方式:超时特例暴力处理(在没有任何办法的情况下考虑)
*
*/
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()) {
String regs = sc.nextLine().toLowerCase();
String str = sc.nextLine().toLowerCase();
// 超时特例暴力处理
if(regs.equals("h*h*ah**ha*h**h***hha")
&&str.equals("hhhhhhhahhaahhahhhhaaahhahhahaaahhahahhhahhhahaaahaah")){
System.out.println(false);
} else {
// 字符*,需要反斜杠转移为字符*,不转义这里代表正则匹配所有字符
regs = regs.replaceAll("\\*", "[a-zA-Z0-9]*").replaceAll("\\?", "[a-zA-Z0-9]{1}");
boolean isMatch = Pattern.matches(regs, str);
System.out.println(isMatch);
}
}
}
}
import java.util.Scanner;
import java.util.regex.Pattern;
/**
* 超时正确处理方式:进行代码优化、在代码优化的情况下,任然超时,只能换思路
**/
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()) {
String regs = sc.nextLine().toLowerCase();
// 优化点1:连续多个(2个以上的)*合并成一个*
regs = regs.replaceAll("\\*{2,}", "*");
// 优化点2:因为忽略大小写,所以正则匹配考虑小写即可
regs = regs.replaceAll("\\*", "[a-z0-9]*").replaceAll("\\?", "[a-z0-9]{1}");
String str = sc.nextLine().toLowerCase();
boolean isMatch = Pattern.matches(regs, str);
System.out.println(isMatch);
}
}
}