题解 | #字符串通配符#
字符串通配符
https://www.nowcoder.com/practice/43072d50a6eb44d2a6c816a283b02036
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String regex = br.readLine().toLowerCase().replaceAll("\\*+","*"); //将多个*替换成单个,减少时间占用
String target = br.readLine().toLowerCase();
System.out.println(check(regex, target));
}
public static boolean check(String regex, String target) {
// if (regex.replace("*", "").length() > target.length()) {
// return false;
// }
int p = 0; //目标字符串指针
int i = 0;//表达式指针
for (; i < regex.length() && p < target.length(); i++) {
char ch = regex.charAt(i);
if (ch == '*') {
//不跳过字符时
if (check(regex.substring(i + 1), target.substring(p))) {
return true;
}
//分别跳过p->target.length()的字符,递归校验,若遇到特殊符号,表示校验失败
for (; p < target.length(); p++) {
char jumpCh = target.charAt(p);
//匹配到了特殊符号
if (!Character.isDigit(jumpCh) && !Character.isLetter(jumpCh)) {
return false;
}
//跳过字符p及以前的字符继续向下匹配
if (check(regex.substring(i + 1), target.substring(p+1))) {
return true;
}
}
return false;
} else if (ch == '?') {
char jumpCh = target.charAt(p);
//匹配到了特殊符号
if (!Character.isDigit(jumpCh) && !Character.isLetter(jumpCh)) {
return false;
}
//跳过一个字符
p++;
} else if (ch == target.charAt(p)) {
//相等,进行下一个字符的匹配
p++;
} else {
//不相等,匹配失败
return false;
}
}
//表达式和目标字符串有一个没用完,表示失败
if (p != target.length() || i != regex.length()) {
return false;
}
return true;
}
}
