You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Given an input string (s) and a pattern (p), 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).
Note:
s could be empty and contains only lowercase letters a-z.
p could be empty and contains only lowercase letters a-z, and characters like . or *.
Example 1:
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
Given an input string (
s
) and a pattern (p
), implement regular expression matching with support for '.
' and '*
'.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:
Example 2:
Example 3:
Example 4:
Example 5:
我没做出来这道Hard难度的题目。这道题难点在于如何分类字符串s和字符串p,然后两两比对。看了大佬的博客,这道题有两种解法。
第一种是暴力递归,将字符串s和p这样分类——对s和p只做最多前两个字符的判断:
这四种情况的判断顺序是从1到4的,如此循环切分判断。
代码如下:
注意Java中的substring函数,如果参数有两个,第一个参数从0开始,包含进得到的子字符串中,第二个参数从0开始,不包含进得到的子字符串中;如果参数只有一个,相当于第二个参数为字符串长度的前者。
第二种方法是动态规划DP。我们从暴力解法可以看出原问题可以分成多个子问题,每个问题由其子问题来决定其解,而且具有无效性,所以可以使用DP解法。
思路是:定义一个二维的 DP 数组,其中 dp[i][j] 表示 s[0,i) 和 p[0,j) 是否匹配,然后有下面三种情况:
DP解法就是暴力递归解法的分类思路,只不过多消耗了空间不用去递归而已。
参考资料:
The text was updated successfully, but these errors were encountered: