演算法與資料結構——正則表示式匹配
阿新 • • 發佈:2018-12-15
1、遞迴方法。
public class Main { public static boolean match(char[] str, char[] pattern) { return match(str, pattern, 0, 0); } public static boolean match(char[] str, char[] pattern, int s, int p) { if (s == str.length && p == pattern.length) { return true; } if (s < str.length && p >= pattern.length) { return false; } if (p < pattern.length - 1 && pattern[p + 1] == '*') { if (s < str.length && (pattern[p] == '.' || str[s] == pattern[p])) return match(str, pattern, s, p + 2) || match(str, pattern, s + 1, p + 2) || match(str, pattern, s + 1, p); else return match(str, pattern, s, p + 2); } if (s < str.length && (pattern[p] == '.' || pattern[p] == str[s])) return match(str, pattern, s + 1, p + 1); return false; } public static void main(String[] args) { String a = ""; String b = ".*"; System.out.println(match(a.toCharArray(), b.toCharArray())); } }