Leetcode - Regular Expression Matching

本文介绍了一种实现正则表达式匹配的算法,支持 '.' 和 '*' 两种特殊字符,其中 '.' 匹配任意单个字符,'*' 匹配零个或多个前导元素。该算法使用动态规划的方法来解决字符串完全匹配的问题,并通过具体实例演示了如何进行匹配判断。

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

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

[balabala] dp[i][j] 表示p的前i个字符能否匹配s的前j个字符。分两大类情况讨论:
1)p的当前字符 != '*': dp[i][j] = dp[i - 1][j - 1] && (currP == currS || currP == '.');
2) p的当前字符 == '*': dp[i][j] 为true的条件是星号要么匹配0次,要么匹配1次,要么匹配多次。匹配多次时根据p的前一个字符分为两种情况:前字符是'.'对s的当前字符无限制, 前字符非 '.'时要求s的当前字符和p的前字符相同
此外,注意到dp[i][0] = dp[i - 2][0] && currp == '*'

public boolean isMatch(String s, String p) {
if (s == null || p == null)
return false;
int lengthS = s.length();
int lengthP = p.length();
boolean[][] dp = new boolean[lengthP + 1][lengthS + 1];
dp[0][0] = true;
for (int i = 1; i <= lengthP ; i++) {
char currP = p.charAt(i - 1);
if (i >= 2) {
dp[i][0] = dp[i - 2][0] && currP == '*';
} else {
dp[i][0] = false;
}
for (int j = 1; j <= lengthS; j++) {
if (currP != '*') {
dp[i][j] = dp[i - 1][j - 1] && (currP == s.charAt(j - 1) || currP == '.');
} else if(i >= 2) {
char lastP = p.charAt(i - 2);
dp[i][j] = dp[i - 2][j] || dp[i - 1][j] || (dp[i][j - 1] && (lastP == '.' || lastP == s.charAt(j - 1)));
}
}
}
return dp[lengthP][lengthS];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值