Leetcode 0010: Regular Expression Matching

本文介绍了LeetCode第0010题——使用动态规划实现正则表达式匹配,包括'.'和'*'的匹配规则。题目要求匹配整个输入字符串,不只部分。通过示例解释了不同情况下的匹配逻辑,并给出了时间复杂度为O(nm)的解决方案。
摘要由CSDN通过智能技术生成

题目描述:

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:

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 {
   
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值