10. Regular Expression Matching
Difficulty: Hard
Given an input string (s
) and a pattern (p
), implement regular expression matching with support for '.'
and '*'
.
1 | '.' Matches any single character. |
The matching should cover the entire input string (not partial).
Note:
s
could be empty and contains only lowercase lettersa-z
.p
could be empty and contains only lowercase lettersa-z
, and characters like.
or*
.
Example 1:
1 | Input: |
Example 2:
1 | Input: |
Example 3:
1 | Input: |
Example 4:
1 | Input: |
Example 5:
1 | Input: |
Solution
Language: Java
1 | class Solution { |
动态规划
使用dp[i][j]
代表s的前i位和p的前j位匹配情况
- 如果
p.charAt(j) == s.charAt(i)
则dp[i + 1][j + 1] = dp[i][j]
; - 如果
p.charAt(j) == '.'
则dp[i + 1][j + 1] = dp[i][j]
; - 如果
p.charAt(j) == '*'
,则分两种情况:- 如果p的j-1位与s的i位不匹配:
那么把星号前的字母当成未出现,dp[i + 1][j + 1] = dp[i + 1][j - 1]
- 否则星号有三种情况,即匹配0次,匹配1次和匹配多次,
1
2
3dp[i + 1][j + 1] = dp[i][j + 1] // 匹配多次
|| dp[i + 1][j - 1] //匹配0次
|| dp[i + 1][j] // 匹配1次
- 如果p的j-1位与s的i位不匹配:
1 | class Solution { |