10. 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

Solution:DP

思路:

Screen Shot 2017-11-21 at 00.50.06.png

reference: https://www.youtube.com/watch?v=DqhPJ8MzDKM
Time Complexity: O(mn) Space Complexity: O(mn)

Solution Code:

class Solution {
    public boolean isMatch(String s, String p) {
        if (s == null || p == null) {
            return false;
        }
        boolean[][] dp = new boolean[p.length() + 1][s.length() + 1];
        dp[0][0] = true;
        // dp init
        for (int i = 1; i <= p.length(); i++) {
            if (p.charAt(i - 1) == '*') {
                dp[i][0] = dp[i - 2][0];
            }
        }
        
        // calc dp
        for (int i = 1 ; i <= p.length(); i++) {
            for (int j = 1; j <= s.length(); j++) {
                if (p.charAt(i - 1) == s.charAt(j - 1) || p.charAt(i - 1) == '.') {
                    dp[i][j] = dp[i - 1][j - 1];
                }
                else if(p.charAt(i - 1) == '*') {
                    if(p.charAt(i - 2) == s.charAt(j - 1) || p.charAt(i - 2) == '.') {
                        dp[i][j] = dp[i][j - 1] || dp[i - 2][j];
                    }
                    else {
                        dp[i][j] = dp[i - 2][j];
                    }
                }
            }
        }
        
        return dp[p.length()][s.length()];
    }
}

你可能感兴趣的:(10. Regular Expression Matching)