java正则表达式匹配leetcode_Leet Code 10 正则表达式匹配 - Java

实现正则表达式匹配,支持 '.' 和 '*'。

'.' 匹配任意单个字符。.

'*' 匹配大于或等于零个前面的元素。

必须匹配整个输入字符串。

一些例子:

isMatch("aa","a") → false

isMatch("aa","aa") → true

isMatch("aaa","aa") → false

isMatch("aa", "a*") → true

isMatch("aa", ".*") → true

isMatch("ab", ".*") → true

isMatch("aab", "c*a*b") → true

第一种方法:暴力递归

Leet Code 测试耗时1293ms。是Leet Code所能接受的最差耗时。

public class Solution {

public static boolean isMatch(String s, String p) {

if (s == null && p == null) {

return true;

}

if (s != null && p == null || s == null && p != null) {

return false;

}

return match(s, 0, p, 0);

}

private static boolean match(String s, int sIndex, String p, int pIndex) {

if (pIndex == p.length()) {

return sIndex == s.length();

}

if (sIndex == s.length()) {

if (pIndex + 1 < p.length() && p.charAt(pIndex + 1) == '*') {

return match(s, sIndex, p, pIndex + 2);

}

return false;

} else {

if (p.charAt(pIndex) == '.') {

if (pIndex + 1 < p.length() && p.charAt(pIndex + 1) == '*') {

return match(s, sIndex + 1, p, pIndex + 2)

|| match(s, sIndex, p, pIndex + 2)

|| match(s, sIndex + 1, p, pIndex);

}

return match(s, sIndex + 1, p, pIndex + 1);

} else {

if (s.charAt(sIndex) != p.charAt(pIndex)) {

if (pIndex + 1 < p.length() && p.charAt(pIndex + 1) == '*') {

return match(s, sIndex, p, pIndex + 2);

} else {

return false;

}

} else {

if (pIndex + 1 < p.length() && p.charAt(pIndex + 1) == '*') {

return match(s, sIndex + 1, p, pIndex + 2)

|| match(s, sIndex, p, pIndex + 2)

|| match(s, sIndex + 1, p, pIndex);

}

return match(s, sIndex + 1, p, pIndex + 1);

}

}

}

}

}

第二种方法:动态规划

Leet Code 测试耗时8ms。

public class Solution {

public static boolean isMatch(String s, String p) {

boolean[][] dp = new boolean[s.length() + 1][p.length() + 1];

dp[0][0] = true;

for (int j = 0; j < p.length(); j++) {

if (p.charAt(j) == '.') {

dp[0][j + 1] = false;

} else if (p.charAt(j) == '*') {

dp[0][j + 1] = j == 0 ? false : dp[0][j - 1];

} else {

dp[0][j + 1] = false;

}

}

for (int i = 0; i < s.length(); i++) {

for (int j = 0; j < p.length(); j++) {

if (p.charAt(j) == '.') {

dp[i + 1][j + 1] = dp[i][j];

} else if (p.charAt(j) == '*') {

if (j == 0) {

dp[i + 1][j + 1] = false;

} else {

if (p.charAt(j - 1) == '.') {

dp[i + 1][j + 1] = dp[i + 1][j - 1] || dp[i + 1][j]

|| dp[i][j + 1];

} else if (p.charAt(j - 1) == s.charAt(i)) {

dp[i + 1][j + 1] = dp[i + 1][j - 1] || dp[i][j + 1];

} else {

dp[i + 1][j + 1] = dp[i + 1][j - 1];

}

}

} else if (p.charAt(j) == s.charAt(i)) {

dp[i + 1][j + 1] = dp[i][j];

} else {

dp[i + 1][j + 1] = false;

}

}

}

return dp[s.length()][p.length()];

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值