10. Regular Expression Matching - jiejackyzhang/leetcode-note GitHub Wiki

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

String类题目

解题思路为Dynamic Programming。

令dp[i][j]表示s的长度为i的起始子串和p的长度为j的起始子串是否match。 则dp[i][j]为true的情况有:

  1. dp[i-1][j-1]==true and (s[i-1]==p[j-1] or p[j-1]=='.')
  2. dp[i-1][j]==true and p[j-1]=='*' and (s[i-1]==p[j-2] or p[j-2]=='.')
  3. dp[i][j-1]==true and p[j-1]=='*' //'*' matches an empty string
  4. dp[i][j-2]==true and p[j-1]=='*' //'a*' matches an empty string

base cases:

  1. dp[0][0]=true
  2. dp[i][0]=false
  3. dp[0][j]=true if (p[j-1]=='*' and m[0][j-2]==true) else false
public class Solution {
    public boolean isMatch(String s, String p) {
        if(s == null || p == null) return false;
        if(s.length() == 0 && p.length() == 0) return true;
        int m = s.length(), n = p.length();
        boolean[][] dp = new boolean[m+1][n+1];
        dp[0][0] = true;
        for(int i = 1; i <= m; i++) dp[i][0] = false;
        for(int j = 2; j <= n; j++) {
            dp[0][j] = (dp[0][j-2] && p.charAt(j-1) == '*');
        }
        for(int i = 1; i <= m; i++) {
            for(int j = 1; j <= n; j++) {
                if((dp[i-1][j-1] && (s.charAt(i-1) == p.charAt(j-1) || p.charAt(j-1) == '.')) 
                || (p.charAt(j-1) == '*' 
                    && ((dp[i-1][j] && (s.charAt(i-1) == p.charAt(j-2) || p.charAt(j-2) == '.'))
                        || (dp[i][j-1] || dp[i][j-2])))) {
                    dp[i][j] = true;
                }
            }
        }
        return dp[m][n];
    }
}
⚠️ **GitHub.com Fallback** ⚠️