【華為機試071】字串萬用字元
阿新 • • 發佈:2018-12-24
題目描述:
在計算機中,萬用字元一種特殊語法,廣泛應用於檔案搜尋、資料庫、正則表示式等領域。現要求各位實現字串萬用字元的演算法。
要求:
實現如下2個萬用字元:
*:匹配0個或以上的字元(字元由英文字母和數字0-9組成,不區分大小寫。下同)
?:匹配1個字元
輸入:
萬用字元表示式;
一組字串。
輸出:
返回匹配的結果,正確輸出true,錯誤輸出false
Java實現:
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { String reg = sc.nextLine(); String str = sc.nextLine(); reg = reg.replace("?", "[0-9a-zA-Z]{1}"); reg = reg.replace("*", "[0-9a-zA-Z]*"); System.out.println(str.matches(reg)); } } }
知識點:
- String的matches函式呼叫了Pattern.matches
- 其原始碼為
public static boolean matches(String regex, CharSequence input) { Pattern p = Pattern.compile(regex); Matcher m = p.matcher(input); return m.matches(); }