LeetCode第[10]题(Java):Regular Expression Matching

题目:匹配正则表达式

题目难度:hard

题目内容: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

我的思路:呵呵哒,没有思路。。。

答案

 1     public boolean isMatch(String text, String pattern) {
 2         if (pattern.isEmpty()) return text.isEmpty();
 3         boolean first_match = (!text.isEmpty() && 
 4                                (pattern.charAt(0) == text.charAt(0) || pattern.charAt(0) == '.'));
 5         
 6         if (pattern.length() >= 2 && pattern.charAt(1) == '*'){
 7             return (isMatch(text, pattern.substring(2)) || 
 8                     (first_match && isMatch(text.substring(1), pattern)));
 9         } else {
10             return first_match && isMatch(text.substring(1), pattern.substring(1));
11         }
12     }

答案思路

1、每个元素逐级向后比较,每一级(元素)都会有一个结果,并且都存在分支判断,如果使用循环来做判断太繁琐,所以可以考虑递归

2、当有多个参数联合判断的时候,首先列表再写判断:(0代表为空)

  text  pattern

  0    0    true

  0    1    first = flase 【可能此时有pattern为x*的情况,而text已经被砍为空了,可能结果为匹配,这种情况应该进入后续的判断】

  1    0    false

  1    1    first = 比较

  根据此表写出判空标准。

3、当前比较结果为字母比较或者当前的pattern为“  .  ”

4、后续比较分两种情况:

  a、此时pattern的前两个为x*,而这种情况的结果为两种结果的或

     i、pattern的x*已经和text中的相应字符匹配完毕,需要进行下一个pattern的匹配,于是将pattern的x*去掉

     ii、pattern的x*与text的当前字母匹配完毕,需要进行下一个text的匹配,于是将当前结果与text去掉一个的结果做结合【当结果为两种时候使用“||”将两种递归相连】

  b、其他情况直接将text与pattern各砍去一个,与当前比较结果结合一起返回。

问:为什么得到当前结果不直接返回?

答:可能此时有pattern为x*的情况,而text已经被砍为空了,可能结果为匹配。只有当pattern为空时不匹配才能直接返回。

原文地址:https://www.cnblogs.com/Xieyang-blog/p/8647620.html