題目描述
問題描述:在計算機中,通配符一種特殊語法,普遍應用於文件搜索、數據庫、正則表達式等領域。現要求各位實現字符串通配符的算法。
要求:
實現以下2個通配符:
*:匹配0個或以上的字符(字符由英文字母和數字0-9組成,不區分大小寫。下同)
?:匹配1個字符
輸入描述
通配符表達式;
一組字符串。
輸出描述
返回匹配的結果,正確輸出true,錯誤輸出false
輸入例子
先輸入一個帶有通配符的字符串,再輸入一個須要匹配的字符串
輸出例子
返回匹配的結果,正確輸出true,錯誤輸出false
算法實現
import java.util.Scanner;
/**
* Declaration: All Rights Reserved !!!
*/
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt"));
while (scanner.hasNext()) {
String reg = scanner.nextLine();
String str = scanner.nextLine();
System.out.println(match(reg, str));
}
scanner.close();
}
private static boolean match(String reg, String str) {
return match(reg, 0, str, 0);
}
private static boolean match(String reg, int i, String str, int j) {
// 正則式已經到達末尾了
if (i >= reg.length()) {
return j >= str.length();
}
// 匹配串已經到達末尾了
if (j >= str.length()) {
return i >= str.length();
}
// 兩個都沒有到末尾
boolean result = false;
switch (reg.charAt(i)) {
case '*':
// 匹配一個字符
result = match(reg, i, str, j + 1);
if (result) {
return true;
}
// 不匹配字符
result = match(reg, i + 1, str, j);
if (result) {
return true;
}
// 只匹配一個字符
result = match(reg, i + 1, str, j + 1);
break;
case '?':
result = match(reg, i + 1, str, j + 1);
break;
default:
if (reg.charAt(i) == str.charAt(j)) {
result = match(reg, i + 1, str, j + 1);
}
}
return result;
}
}