Regular Expression Matching
Question
Solution
Implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
Hide Tags Dynamic Programming Backtracking String
SOLUTION1:
总的来说思路是递归。
判断下一个字符是否是*:
如果不是*,则判断当前字符是否匹配。
如果是*,则因为不能确定*到底会匹配几个,在当前字符匹配的前提下,要枚举所有的情况,从假设匹配0个,1个,2个。。。只要有一种情况成功了,最终也就成功了。
我们可以从0开始,先考虑直接跳过当前2个正则字符,然后再1个,2个继续搜索下去。
如果是*,但是当前字符不匹配,则跳过两个递归。
具体的代码如下,注释写得很清楚。
ref: http://blog.csdn.net/fightforyourdream/article/details/17717873
1 package Algorithms; 2 3 public class IsMach { 4 public static void main(String[] str) { 5 //System.out.println(isMatch("aa", "aa")); 6 System.out.println(isMatch("aab", "c*a*b")); 7 } 8 9 public static boolean isMatch(String s, String p) { 10 if (s == null || p == null) { 11 return false; 12 } 13 14 return help(s, p, 0, 0); 15 } 16 17 public static boolean help(String s, String p, int indexS, int indexP) { 18 int pLen = p.length(); 19 int sLen = s.length(); 20 21 // 1. P结束了,这时 S也应该要结束 22 if (indexP == pLen) { 23 return indexS == sLen; 24 } 25 26 // 2. P 只有最后一个没有匹配 27 if (indexP == pLen - 1) { 28 // 必须相等,或者是p为'.'. 29 // S必须只有一个字符 30 return indexS == sLen - 1 && matchChar(s, p, indexS, indexP); 31 } 32 33 // 以下P 至少还有2个字符. 34 35 // 2. 单独匹配的情况, 如 aa, a. 类似这样 36 if (p.charAt(indexP + 1) != '*') { 37 if (indexS < sLen && matchChar(s, p, indexS, indexP)) { 38 return help(s, p, indexS + 1, indexP + 1); // p可以前进一格 39 } else { 40 return false; 41 } 42 } 43 44 // 3. 多重匹配的情况, 如 .* or a* ,这时需要进行递归 45 46 // 先直接跳过此2个正则,因为我们可以匹配空。 47 if (help(s, p, indexS, indexP + 2)) { 48 return true; 49 } 50 51 // 匹配非空的情况,这里不可以跳过p,必须 匹配1个或是多个 52 for (int i = indexS; i < sLen; i++) { 53 if (!matchChar(s, p, i, indexP)) { 54 return false; 55 } else { 56 if (help(s, p, i + 1, indexP + 2)) { 57 return true; 58 } 59 } 60 } 61 62 // 多重匹配之后,余下的字串仍然不可以匹配,则返回失败。 63 return false; 64 } 65 66 // check if the s match p in the index. 67 public static boolean matchChar(String s, String p, int indexS, int indexP) { 68 return (s.charAt(indexS) == p.charAt(indexP)) || p.charAt(indexP) == '.'; 69 } 70 }