10. Regular Expression Matching

Description

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, time O(m * n), space O(m * n)

以前用DFS就可以AC,但是现在会TLE,必须祭出DP大法啦。
注意必须预处理j = 0的情况!考虑s = "", p = "a*",如果没有预处理,则结果会返回F。

  1. If p.charAt(j) == s.charAt(i) : dp[i][j] = dp[i-1][j-1];
  2. If p.charAt(j) == '.' : dp[i][j] = dp[i-1][j-1];
  3. If p.charAt(j) == '*': here are two sub conditions:
    • if p.charAt(j-1) != s.charAt(i) : dp[i][j] = dp[i][j-2] //in this case, a* only counts as empty
    • if p.charAt(i-1) == s.charAt(i) or p.charAt(i-1) == '.':
      • dp[i][j] = dp[i - 1][j] //in this case, a* counts as multiple a
      • or dp[i][j] = dp[i][j - 2] // in this case, a* counts as empty
class Solution {
    public boolean isMatch(String s, String p) {
        if (s == null || p == null) {
            return false;
        }
        
        int m = s.length();
        int n = p.length();
        boolean[][] dp = new boolean[m + 1][n + 1];
        dp[0][0] = true;
        // only when p is like "a*b*c*" could match empty str
        for (int j = 1; j < n; j += 2) {
            if (p.charAt(j) == '*' && dp[0][j - 1]) {
                dp[0][j + 1] = true;
            }
        }
        
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (s.charAt(i) == p.charAt(j) || p.charAt(j) == '.') {
                    dp[i + 1][j + 1] = dp[i][j];
                }  else if (p.charAt(j) == '*') {
                    dp[i + 1][j + 1] = dp[i + 1][j - 1];    // match empty
                    if (p.charAt(j - 1) == s.charAt(i) || p.charAt(j - 1) == '.') {
                        dp[i + 1][j + 1] =  dp[i + 1][j + 1] || dp[i][j + 1];   // match multiple
                    }
                }
            }
        }
        
        return dp[m][n];
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容