Leetcode 0010: Regular Expression Matching

题目描述:

Given an input string s and a pattern p, implement regular expression matching with support for ’ . ’ and ‘ * ‘ where:
‘.’ Matches any single character.​​​​
‘*’ Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).

Example 1:

Input: s = “aa”, p = “a”
Output: false
Explanation: “a” does not match the entire string “aa”.

Example 2:

Input: s = “aa”, p = “a*”
Output: true
Explanation: ‘*’ means zero or more of the preceding element, ‘a’. Therefore, by repeating ‘a’ once, it becomes “aa”.

Example 3:

Input: s = “ab”, p = “."
Output: true
Explanation: ".
” means “zero or more (*) of any character (.)”.

Example 4:

Input: s = “aab”, p = “c * a * b”
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore, it matches “aab”.

Example 5:

扫描二维码关注公众号,回复: 12517429 查看本文章

Input: s = “mississippi”, p = “mis * is * p *”
Output: false

Constraints:

0 <= s.length <= 20
0 <= p.length <= 30
s contains only lowercase English letters.
p contains only lowercase English letters, ‘.’, and ’ * '.
It is guaranteed for each appearance of the character ‘*’, there will be a previous valid character to match.

Time complexity: O(nm)
动态规划:
状态表示:dp[i][j]表示s的前i了字母是否能匹配p的前j个字母
状态转移:
如果p[j]不是通配符 ’ * ‘,则当且仅当s[i]可以和p[j]匹配,且dp[i-1][j-1]是真, 则dp[i][j]是真;
如果p[j]是通配符’ * ',则有下面的两种情况:

  1. 字符s[i] != p[j-1]: 在这种情况下 p[j-1]p[j] 可以看作是 空字符 则:dp[i][j] = dp[i][j-2]
  2. 字符s[i] == p[j-1] 或者 p[j-1] == ‘.’ 把p[j-1]假设为字符a,则:
    (1) dp[i][j] = dp[i-1][j] a* 可以匹配多个字符串 aaaa
    (2) dp[i][j] = dp[i][j-1] a* 可以匹配单个字符 a
    (3) dp[i][j] = dp[i][j-2] a* 可以匹配空字符

注意在 初始化dp时 因为 通配符’ * '加上它的前一个字符匹配空字符,所以要先初始化所有p的所有偶数长度的子符串

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 j = 1; j < m; j += 2){
    
    
            dp[0][j+1] = p.charAt(j) == '*' && dp[0][j-1];
        }
        for(int i = 1; i <= n; i++){
    
    
            for(int j = 1; j <= m; j++){
    
    
                if(s.charAt(i-1) == p.charAt(j-1) || p.charAt(j-1) == '.'){
    
    
                    dp[i][j] = dp[i-1][j-1];
                }else if(p.charAt(j-1) == '*'){
    
    
                    if(p.charAt(j-2) != s.charAt(i-1) && p.charAt(j-2) != '.'){
    
    
                        dp[i][j] = dp[i][j-2];
                    }else{
    
    
                        dp[i][j] = (dp[i][j - 2] || dp[i - 1][j - 2] || dp[i - 1][j]);
                    }
                }
            }
        }
        return dp[n][m];
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43946031/article/details/113821609
今日推荐