shopee 笔试最后一题求 AC 解
通配符匹配。 输入两行字符串,第一行是正则表达式,第二行是不含通配符的字符串。如果完全匹配输出 1,否则输出 0.
? 匹配一个字符
# 匹配 0 或 1 个字符
* 匹配 0 或多个字符
个人只有77%🤣🤣
import java.util.*;
public class Main {
public static void main(String[] args){
Scanner scanner=new Scanner(System.in);
//while (true) {
String reg = scanner.nextLine();
String str = scanner.nextLine();
//* ? -
// if(reg.equals("."))
// break;
int i = 0, j = 0;
if (match(reg, str, 0, 0))
System.out.println(1);
else
System.out.println(0);
// }
}
public static boolean match(String reg,String str,int i,int j){
if(reg.length()==i && str.length()==j)
return true;
if(reg.length()==i && str.length()!=j)
return true;
if(reg.length()!=i && str.length()==j){
for(int p=i;p<reg.length();p++){
char c=reg.charAt(p);
if(c!='*' && c!='#')
return true;
}
return true;
}
switch (reg.charAt(i)){
case '?':
return match(reg,str,i+1,j+1);
case '#':
return match(reg,str,i+1,j+1) || match(reg,str,i+1,j);
case '*':
while (i<reg.length() && reg.charAt(i)=='*' )
i++;
for(int p=j;p<str.length();p++){
if(match(reg,str,i,p))
return true;
}
return false;
default:return reg.charAt(i)==str.charAt(j) && match(reg,str,i+1,j+1);
}
}
}
查看6道真题和解析