题解 | #字符串通配符#
字符串通配符
https://www.nowcoder.com/practice/43072d50a6eb44d2a6c816a283b02036
import java.util.Scanner;
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine()) { // 注意 while 处理多个 case
String a = in.nextLine();
String b = in.nextLine();
Character c1 = '*';
Character c2 = '?';
a = a.toLowerCase();
b = b.toLowerCase();
//去除多余的*,提高性能
int count = 0;
char[] ca = a.toCharArray();
for (int i = 0;i + count < ca.length;i++){
while (i + count < ca.length-1 && ca[i] == ca[i+count+1] && ca[i] == '*'){
count++;
}
ca[i] = ca[i+count];
}
a = new String(ca,0, ca.length - count);
System.out.println(match(a, b));
}
}
private static boolean match (String s1, String s2) {
//一系列递归出口
if ("*".equals(s1) && (s2 == null || s2.length() == 0)){
return true;
}
if ((s1 == null || s1.length() == 0 ) && (s2 == null || s2.length() == 0) ) {
return true;
}
if ((s1 != null || s1.length() != 0 ) && (s2 == null || s2.length() == 0) ) {
return false;
}
if ((s1 == null || s1.length() == 0 ) && (s2 != null || s2.length() != 0) ) {
return false;
}
if (("?".equals(s1) && (
(s2.charAt(0) >= 'a' && s2.charAt(0) <= 'z')
|| (s2.charAt(0) >= '0' && s2.charAt(0) <= '9')
)) && s2.length() == 1) {
return true;
}
//分为两种,一个是算上*,匹配字符从第二个开始,一个是认为*没有匹配,当然要考虑题目里匹配的限制
if ('*' == s1.charAt(0)) {
return ( (
(s2.charAt(0) >= 'a' && s2.charAt(0) <= 'z')
|| (s2.charAt(0) >= '0' && s2.charAt(0) <= '9')
) && match(s1, s2.substring(1)))
|| match(s1.substring(1), s2)
;
}
if (s1.charAt(0) == s2.charAt(0)
|| ('?' == s1.charAt(0)
&& (
(s2.charAt(0) >= 'a' && s2.charAt(0) <= 'z')
|| (s2.charAt(0) >= '0' && s2.charAt(0) <= '9')
)
)) {
return match(s1.substring(1), s2.substring(1));
}
return false;
}
}
查看14道真题和解析
