题解 | #字符串通配符#
字符串通配符
https://www.nowcoder.com/practice/43072d50a6eb44d2a6c816a283b02036
动态规划
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String pattern = in.nextLine();
String str = in.nextLine();
int[][] dpl = new int[pattern.length()+1][str.length()+1];
dpl[0][0] = 1;
//动态规划 dpl[i][j]的值与dpl[i-1][j-1] dpl[i][j-1] 和 dpl[i-1][j] 有关
for(int i=1;i<dpl.length;i++){
for(int j=0;j<dpl[0].length;j++){
char cp = pattern.charAt(i-1);
if(j==0){
if(cp=='*'&&dpl[i-1][j]==1){
dpl[i][j]=1;
}
continue;
}
char cs = str.charAt(j-1);
if(dpl[i-1][j-1]==1){
if(match(cp,cs)||equal(cp,cs)){
dpl[i][j] = 1;
continue;
}else if(cp==cs){
dpl[i][j] = 1;
continue;
}
}
if(dpl[i][j-1]==1 && match(cp,cs)){
dpl[i][j] = 1;
continue;
}
if(dpl[i-1][j]==1 && match(cp,cs)){
dpl[i][j] = 1;
continue;
}
}
}
int res = dpl[pattern.length()][str.length()];
System.out.println(res==1);
}
// 判断是否满足通配符通配格式,仅仅第一行为*和?不能说明匹配,还要验证"字符仅由英文字母和数字0到9组成"
public static boolean match(char p,char c){
if((p=='*' || p == '?')&&
(
(c>='0'&&c<='9')||
(c>='a'&&c<='z')||
(c>='A'&&c<='Z')
)
){
return true;
}else{
return false;
}
}
// 判断字符与匹配字符是否相等,要求无视大小写
public static boolean equal(char p,char c){
if(p==c){
return true;
}else if(p>='a'&&p<='z' && c>='A'&&c<='Z' && (p-32)==c){
return true;
}else if(c>='a'&&c<='z' && p>='A'&&p<='Z' && (c-32)==p){
return true;
}
return false;
}
}
查看5道真题和解析