[eetcode 10]Regular Expression Matching

1 题目:

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

2 思路:

好吧,这题我开始一个一个比较真是跪了,没有用递归,考虑各种情况,各种if-else,发现还是无法考虑所有情况。看别人写的,使用递归写的,思路很清楚。

https://leetcode.com/discuss/32424/clean-java-solution

看那个c++的,想转为java,真是跪了,c++用''表示字符串结束,而java字符串是数组,没有这个一说,各种越界加超时。

https://leetcode.com/discuss/9405/the-shortest-ac-code

3 代码:

    public boolean isMatch(String s, String p) {
        if (p.isEmpty()) {
            return s.isEmpty();
        }

        if (p.length() == 1 || p.charAt(1) != '*') {
            if (s.isEmpty() || (p.charAt(0) != '.' && p.charAt(0) != s.charAt(0))) {
                return false;
            } else {
                return isMatch(s.substring(1), p.substring(1));
            }
        }

        //P.length() >=2 && p.charAt(1) == '*'
        //                       the first char is match
        while (!s.isEmpty() && (s.charAt(0) == p.charAt(0) || p.charAt(0) == '.')) {  
            if (isMatch(s, p.substring(2))) { 
                return true;                     
            }
            //see if the next char of s is still match
            s = s.substring(1);
        }
        //first char not match  , make * to 0
        return isMatch(s, p.substring(2));
    }


原文地址:https://www.cnblogs.com/lingtingvfengsheng/p/4565666.html