问题描述:在计算机中,通配符一种特殊语法,广泛应用于文件搜索、数据库、正则表达式等领域。现要求各位实现字符串通配符的算法。
要求:
实现如下2个通配符:
*:匹配0个或以上的字符(字符由英文字母和数字0-9组成,不区分大小写。下同)
?:匹配1个字符
输入:
通配符表达式;
一组字符串。
输出:
返回匹配的结果,正确输出true,错误输出false
本题含有多组样例输入!
输入描述:
先输入一个带有通配符的字符串,再输入一个需要匹配的字符串
输出描述:
返回匹配的结果,正确输出true,错误输出false
示例1
输入
te?t*.*
txt12.xls
输出
false
package TE0508;
import java.util.*;
public class Main {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
String str=sc.nextLine();
String str1=sc.nextLine();
System.out.println(slove2(str,str1));
// int n=sc.nextInt();
// slove(n);
}
}
/*
牛客统计每个月兔子的总数
*/
public static void slove(int n){
//a是一个月大的兔子
int a=1;
//b是两个月大的兔子
int b=0;
//c是三个月以上的兔子
int c=0;
for(int i=1;i<n;i++){
c+=b;
b=a;
a=c;
}
System.out.println(a+b+c);
}
/*
牛客 字符串通配符
*/
public static boolean slove2(String str,String str1) {
char[] ch1 = str.toCharArray();
char[] ch2 = str1.toCharArray();
int demo = 0;
int length = str1.length();
for (int i = 0; i < length; i++) {
//当前ch1[demo]不是'*'、'?'并且与ch2[i]不想等则返回false
if (ch1[demo] != '*' && ch1[demo] != '?' && ch1[i] != ch2[i]) {
return false;
}
//当前ch1[demo]位置是'?'或者ch1[demo]等于ch2[i]则demo+1
if (ch1[demo] == '?' || ch1[demo] == ch2[i]) {
demo++;
continue;
}
//当前ch1[demo]是'*',则判断ch1[demo+1]位置和ch2[i+1]是否相等,若相等则demo+1,不想等则继续遍历ch2数组
if (demo + 1 < length && i + 1 < length) {
if (ch1[demo+1]==ch2[i+1]){
demo++;
continue;
}
}
if (ch1[demo]=='*'){
continue;
}
}
return true;
}
}