给你一个字符串 s 和一个字符规律 p,请你来实现一个支持 '.' 和 '*' 的正则表达式匹配
https://leetcode-cn.com/problems/regular-expression-matching/
'.' 匹配任意单个字符
'*' 匹配零个或多个前面的那一个元素
示例1:
输入:s = "aa" p = "a"
输出:false
解释:"a" 无法匹配 "aa" 整个字符串。
示例2:
输入:s = "aa" p = "a"
输出:true
解释:因为 '' 代表可以匹配零个或多个前面的那一个元素, 在这里前面的元素就是 'a'。因此,字符串 "aa" 可被视为 'a' 重复了一次。
示例3:
输入:s = "ab" p = "."
输出:true
解释:"." 表示可匹配零个或多个('*')任意字符('.')。
示例4:
输入:s = "aab" p = "cab"
输出:true
解释:因为 '*' 表示零个或多个,这里 'c' 为 0 个, 'a' 被重复一次。因此可以匹配字符串 "aab"。
示例 5:
输入:s = "mississippi" p = "misisp*."
输出:false
提示:
0 <= s.length <= 20
0 <= p.length <= 30
s 可能为空,且只包含从 a-z 的小写字母。
p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 *。
保证每次出现字符 * 时,前面都匹配到有效的字符
Java解法
思路:
- 之前做过类似的,可以通过动态规划来枚举所有,直到找到或不存在
- 脑壳疼,动态方程未算出,参考官方解
package sj.shimmer.algorithm.y2021;
/**
* Created by SJ on 2021/3/16.
*/
class D50 {
public static void main(String[] args) {
System.out.println(isMatch("aa", "a"));
System.out.println(isMatch("aa", "a*"));
System.out.println(isMatch("ab", ".*"));
System.out.println(isMatch("aab", "c*a*b"));
System.out.println(isMatch("mississippi", "mis*is*p*."));
System.out.println(isMatch("aa", "aaa"));
System.out.println(isMatch("aaa", "a*a"));
}
public static boolean isMatch(String s, String p) {
int m = s.length();
int n = p.length();
boolean[][] f = new boolean[m + 1][n + 1];
f[0][0] = true;
for (int i = 0; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (p.charAt(j - 1) == '*') {
f[i][j] = f[i][j - 2];
if (matches(s, p, i, j - 1)) {
f[i][j] = f[i][j] || f[i - 1][j];
}
} else {
if (matches(s, p, i, j)) {
f[i][j] = f[i - 1][j - 1];
}
}
}
}
return f[m][n];
}
public static boolean matches(String s, String p, int i, int j) {
if (i == 0) {
return false;
}
if (p.charAt(j - 1) == '.') {
return true;
}
return s.charAt(i - 1) == p.charAt(j - 1);
}
}

官方解
-
动态规划
详见链接
-
时间复杂度:O(mn)
-
空间复杂度:O(mn)
-
网友评论