leet-code/src/main/java/leetcode/editor/cn/RegularExpressionMatching.java

126 lines
3.6 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//给你一个字符串 s 和一个字符规律 p请你来实现一个支持 '.' 和 '*' 的正则表达式匹配。
//
//
// '.' 匹配任意单个字符
// '*' 匹配零个或多个前面的那一个元素
//
//
// 所谓匹配,是要涵盖 整个 字符串 s的而不是部分字符串。
//
//
// 示例 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 = "c*a*b"
//输出true
//解释:因为 '*' 表示零个或多个,这里 'c' 为 0 个, 'a' 被重复一次。因此可以匹配字符串 "aab"。
//
//
// 示例 5
//
//
//输入s = "mississippi" p = "mis*is*p*."
//输出false
//
//
//
// 提示:
//
//
// 0 <= s.length <= 20
// 0 <= p.length <= 30
// s 可能为空,且只包含从 a-z 的小写字母。
// p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 *。
// 保证每次出现字符 * 时,前面都匹配到有效的字符
//
// Related Topics 字符串 动态规划 回溯算法
// 👍 2074 👎 0
package leetcode.editor.cn;
//10:正则表达式匹配
public class RegularExpressionMatching {
public static void main(String[] args) {
//测试代码
Solution solution = new RegularExpressionMatching().new Solution();
//false
System.out.println(solution.isMatch("aa", "a"));
//true
System.out.println(solution.isMatch("aa", "a*"));
//true
System.out.println(solution.isMatch("aa", ".*"));
//true
System.out.println(solution.isMatch("ab", ".*"));
//false
System.out.println(solution.isMatch("aa", "a"));
//true
System.out.println(solution.isMatch("aab", "c*a*b"));
//false
System.out.println(solution.isMatch("aaa", "aaaa"));
//false
System.out.println(solution.isMatch("a", "ab*a"));
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public boolean isMatch(String s, String p) {
int sLength = s.length();
int pLength = p.length();
boolean[][] f = new boolean[sLength + 1][pLength + 1];
f[0][0] = true;
for (int i = 0; i <= sLength; ++i) {
for (int j = 1; j <= pLength; ++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[sLength][pLength];
}
public 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);
}
}
//leetcode submit region end(Prohibit modification and deletion)
}