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

就是说写一个类似于正则匹配中. 和 * 的规则解析,"." 匹配 任意字符,"*"匹配0个或者多个。

思路

用dp[i][j]表示text[0, i) 和 pattern[0, j)是否匹配,于是有以下三种情况

  1. dp(i, j) = dp(i-1, j-1)
    if p[j-1] != * && (p[j-1] == t[i-1] || p[j-1] == "."
  2. dp(i,j) = dp(i, j-2)
    if p[j-1] == * && 至少匹配0次
  3. dp(i,j) = dp(i-1, j) && (t[i-1] == p[j-2] || p[j-2] = ".")
    if p[j-1] == * && 至少匹配1次

代码

class Solution {
        
    public boolean isMatch(String s, String p) {
        int n = s.length();
        int m = p.length();
        boolean[][] dp = new boolean[n+1][m+1];
        dp[0][0] = true;
        for (int i = 0; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                if (p.charAt(j-1) == '*') {
                    dp[i][j] = dp[i][j-2] || (i > 0 && (s.charAt(i-1)==p.charAt(j-2) || p.charAt(j-2)=='.') && dp[i-1][j]);
                }else{
                    dp[i][j] = i > 0 && (s.charAt(i-1) == p.charAt(j-1) || p.charAt(j-1) == '.') && dp[i-1][j-1];
                }
            }
        }
        return dp[n][m];
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容