LeetCode正则表达式匹配

本文解析了如何使用动态规划解决LeetCode中的正则表达式匹配问题,通过实例展示了'.'和'*'通配符的处理技巧。重点介绍了dp数组的初始化、边界条件和状态转移方程,最终目标是判断整个输入字符串是否与模式完全匹配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode: 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).

Example1

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

Example2

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

Example3

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

方法思路
采用dp动态规划的方法,分为三部,设置base case(基础情况),update function(迭代函数)以及goal(return value)。base case即考虑一些特殊情况,在update function中的循环遍历中,从子数组向整个数组推进,每次都进行match

代码如下(示例):

/*
    dp[i][j] = 比较长度为i的s字符串和长度为j的p字符串是否相等
*/

class Solution {
    public boolean isMatch(String s, String p) {
        //以长度为基准,所以起始为1
        boolean[][] dp = new boolean[s.length()+1][p.length()+1];
        //Base case
        //字符串s和字符串p的长度都为0,匹配成功
        dp[0][0] = true;
        //字符串s的长度为0但是p的最后两个字符为x和*,x*可以被看作空,所以只需要比较去掉这两个字符的字符串p
        for(int i = 1; i <= p.length(); i++){
            if(p.charAt(i-1)=='*' && dp[0][i-2]){
                dp[0][i] = true;
            }
        }
        //遍历两个字符串
        for(int i = 1; i <= s.length(); i++){
            for(int j = 1; j <= p.length(); j++){
            	//如果s的子串最后一个字符和p子串的最后一个字符都是小写字母并且相等或者p子串的最后一个字符是.
                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) == '*'){
                    //p最后两个数表示为x*,s最后一个数表示为y,如果 x != y并且x不是.
                    if(p.charAt(j-2) != s.charAt(i-1) && p.charAt(j-2) != '.'){
                        dp[i][j] = dp[i][j-2]; //直接将x*视为空
                    }
                    //如果x=y
                    else{
                        //存在三种情况,检擦所有三种情况
                        //1 *表示0个x 这种情况和之前类似 dp[i][j] = dp[i][j-2]
                        //2 *表示1个x 这种情况可直接忽略*进行比较 dp[i][j] = dp[i][j-1]
                        //3 *表示多个x 就表示s中最后存在多个x那么先去掉这些x,因为p中的x*可表示为0个
                        dp[i][j] = (dp[i][j-2] || dp[i][j-1] || dp[i-1][j]);
                    }
                }
            }
        }
        return dp[s.length()][p.length()];
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值