|
| 1 | +/** |
| 2 | + * mplement regular expression matching with support for '.' and '*'. |
| 3 | + * '.' Matches any single character. |
| 4 | + * '*' Matches zero or more of the preceding element. |
| 5 | + * <p/> |
| 6 | + * The matching should cover the entire input string (not partial). |
| 7 | + * <p/> |
| 8 | + * The function prototype should be: |
| 9 | + * bool isMatch(const char *s, const char *p) |
| 10 | + * <p/> |
| 11 | + * Some examples: |
| 12 | + * isMatch("aa","a") ? false |
| 13 | + * isMatch("aa","aa") ? true |
| 14 | + * isMatch("aaa","aa") ? false |
| 15 | + * isMatch("aa", "a*") ? true |
| 16 | + * isMatch("aa", ".*") ? true |
| 17 | + * isMatch("ab", ".*") ? true |
| 18 | + * isMatch("aab", "c*a*b") ? true |
| 19 | + */ |
| 20 | +public class RegexMatch { |
| 21 | + public static void main(String[] args) { |
| 22 | + // boolean match = isMatch("aa","aa"); |
| 23 | + // boolean match = isMatch("aaa","aa"); |
| 24 | + // boolean match = isMatch("aa", "a*"); |
| 25 | + // boolean match = isMatch("aa", ".*"); |
| 26 | + boolean match = isMatch("ab", ".*"); |
| 27 | + // boolean match = isMatch("aab", "c*a*b"); |
| 28 | + System.out.println(match); |
| 29 | + |
| 30 | + } |
| 31 | + |
| 32 | + public static boolean isMatch(String s, String p) { |
| 33 | + if (s == null || p == null) return false; |
| 34 | + if (p.isEmpty()) return s.isEmpty(); |
| 35 | + |
| 36 | + if (p.length() >= 2) { |
| 37 | + if (p.charAt(1) == '*') { |
| 38 | + if (!s.isEmpty()) { |
| 39 | + if (p.charAt(0) == '.' || p.charAt(0) == s.charAt(0)) |
| 40 | + return isMatch(s.substring(1), p) || isMatch(s, p.substring(2)); |
| 41 | + else |
| 42 | + return isMatch(s, p.substring(2)); |
| 43 | + } else |
| 44 | + return true; // s:"", p:"a*" || ".*" |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + // p is not empty, at least 1 |
| 49 | + if (p.charAt(0) == '.') { |
| 50 | + if (s.isEmpty()) return false; // s:"", p:"." |
| 51 | + else return isMatch(s.substring(1), p.substring(1)); |
| 52 | + } |
| 53 | + |
| 54 | + if (s.charAt(0) != p.charAt(0)) return false; |
| 55 | + |
| 56 | + return isMatch(s.substring(1), p.substring(1)); |
| 57 | + } |
| 58 | +} |
0 commit comments