实现正则表达式匹配,支持 '.' 和 '*'。
'.' 匹配任意单个字符。.
'*' 匹配大于或等于零个前面的元素。
必须匹配整个输入字符串。
一些例子:
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()];
}
}