Leecode 0010. Regular Expression Matching
10. 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:
1 | Input: s = "aa", p = "a" |
Example 2:
1 | Input: s = "aa", p = "a*" |
Example 3:
1 | Input: s = "ab", p = ".*" |
算法思路
采用动态规划(DP)的方法解决这个问题:
- 定义状态
dp[i][j]
表示 s 的前 i 个字符与 p 的前 j 个字符是否匹配 - 初始化边界条件:空字符串与空模式匹配,即
dp[0][0] = true
- 处理 '*' 号的特殊情况:
- '*' 可以匹配 0 个前面的元素:
dp[i][j] = dp[i][j-2]
- '*' 可以匹配 1 个或多个前面的元素(需当前字符匹配):
dp[i][j] = dp[i-1][j]
- '*' 可以匹配 0 个前面的元素:
- 处理普通字符和 '.' 的匹配情况
1 | class Solution { |
代码解析
DP 表定义:
dp[i][j]
表示 s 的前 i 个字符(s [0..i-1])与 p 的前 j 个字符(p [0..j-1])是否匹配
边界条件处理:
空字符串与空模式匹配:
dp[0][0] = true
对于模式中的 '*',可以匹配 0 个前面的元素,所以
dp[0][j] = dp[0][j-2]
状态转移:
当当前字符匹配(相同或模式为 '.'):
dp[i][j] = dp[i-1][j-1]
当模式字符为 '*' 时:
- 匹配 0 个前面的元素:
dp[i][j] = dp[i][j-2]
- 若当前字符与 '*' 前面的字符匹配,还可以匹配 1 个或多个:
dp[i][j] |= dp[i-1][j]
- 匹配 0 个前面的元素:
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.