Leetcode - Regular Expression Matching

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

[balabala] dp[i][j] 表示p的前i个字符能否匹配s的前j个字符。分两大类情况讨论:
1)p的当前字符 != '*': dp[i][j] = dp[i - 1][j - 1] && (currP == currS || currP == '.');
2) p的当前字符 == '*': dp[i][j] 为true的条件是星号要么匹配0次,要么匹配1次,要么匹配多次。匹配多次时根据p的前一个字符分为两种情况:前字符是'.'对s的当前字符无限制, 前字符非 '.'时要求s的当前字符和p的前字符相同
此外,注意到dp[i][0] = dp[i - 2][0] && currp == '*'

public boolean isMatch(String s, String p) {
        if (s == null || p == null)
            return false;
        int lengthS = s.length();
        int lengthP = p.length();
        boolean[][] dp = new boolean[lengthP + 1][lengthS + 1];
        dp[0][0] = true;
        for (int i = 1; i <= lengthP ; i++) {
            char currP = p.charAt(i - 1);
            if (i >= 2) {
                dp[i][0] = dp[i - 2][0] && currP == '*'; 
            } else {
                dp[i][0] = false;
            }
            for (int j = 1; j <= lengthS; j++) {
                if (currP != '*') {
                    dp[i][j] = dp[i - 1][j - 1] && (currP == s.charAt(j - 1) || currP == '.');
                } else if(i >= 2) {
                    char lastP = p.charAt(i - 2);
                    dp[i][j] = dp[i - 2][j] || dp[i - 1][j] || (dp[i][j - 1] && (lastP == '.' || lastP == s.charAt(j - 1)));
                }
            }
        }
        return dp[lengthP][lengthS];
}

猜你喜欢

转载自likesky3.iteye.com/blog/2211757