试题
判断两个字符串能否完全匹配的上
?
匹配任意字符一次 如 a?c abc
#
匹配任意字符0次或一次 如 a#c ac abc
*
匹配任意字符0次或无限次 如 a*c ac abc abbbbc
代码
过了96%,可能还有些边界。
这一题显然每次遇到匹配符的时候都有几种可能的组合形式,所以我们使用递归把每种情况的搜一下。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str1 = in.nextLine();
String str2 = in.nextLine();
int len1 = str1.length();
int len2 = str2.length();
if(compare(str1, str2, 0, 0, len1, len2))
System.out.print(1);
else
System.out.print(0);
}
public static boolean compare(String s1, String s2, int t1, int t2, int l1, int l2){
//终止条件是两个字符串都遍历到了尾部
if(l1 == t1 && l2 == t2){
return true;
}
//匹配一个字符情况,这里要保证在s1为?时,t2必须也要小于l2,因为s2中需要有个字符跳过
if(t1 < l1 && t2 < l2 && (s1.charAt(t1) == s2.charAt(t2) || s1.charAt(t1) == '?') ){
if(compare(s1, s2, t1+1, t2+1, l1, l2)) return true;
//同理t2<l2,这样就能保证调用compare时t1,t2不会超过字符串长度,我们的递归的终止条件就不用考虑其他情况。
}else if(t1 < l1 && s1.charAt(t1) == '#'){
if(compare(s1, s2, t1+1, t2, l1, l2)) return true;
if(t2 < l2 && compare(s1, s2, t1+1, t2+1, l1, l2)) return true;
}else if(t1 < l1 && s1.charAt(t1) == '*'){
if(compare(s1, s2, t1+1, t2, l1, l2)) return true;
int nxt = t2;
//匹配任意多次的情况
while(nxt < l2 && s2.charAt(t2) == s2.charAt(nxt)){
if(compare(s1, s2, t1+1, nxt+1, l1, l2)) return true;
nxt++;
}
}
return false;
}
}