参考https://www.jianshu.com/p/96f25c12716a的思路
这里就是非贪心的匹配方式,代码量很少,每次只匹配开头的字符,剩余结果由回溯过程得到。
思路:反向dp,这里我们如果用dp的思想,那么dp[i][j]表示的是text[i:]和pattern[j:]是否匹配,求的其实是dp[0][0],所以是一种反向的dp,题目中无论是自底向上的方法还是从顶往下的方法,其计算顺序其实都是反向的(最后得到的结果都是dp[0][0]),这里自底向上的方法中,Result枚举的意义其实只是封装了一个布尔值,相当于一个布尔封装类型的数组
//str.substr(n)使用很方便,相当于删除前n个字符
class Solution {
public boolean isMatch(String text, String pattern) {
if (pattern.isEmpty()) return text.isEmpty();
boolean first_match = (!text.isEmpty() &&
(pattern.charAt(0) == text.charAt(0) || pattern.charAt(0) == '.'));
if (pattern.length() >= 2 && pattern.charAt(1) == '*'){
return (isMatch(text, pattern.substring(2)) || //这里的 || 代表回溯过程
(first_match && isMatch(text.substring(1), pattern)));
} else {
return first_match && isMatch(text.substring(1), pattern.substring(1));
}
}
}
这是保存的做法,从底向上
class Solution {
public:
bool isMatch(string s, string p) {
bool **dp = (bool**)malloc(sizeof(bool*)*(s.length()+1));
for (int i = 0; i < s.length() + 1; i++)
dp[i] = (bool*)malloc(sizeof(bool)*(p.length()+1));
dp[s.length()][p.length()] = true;
for (int i = s.length(); i >= 0; i--) {
for (int j = p.length() - 1; j >= 0; j--) {
bool first_match = (i < s.length() &&
(p[j] == s[i] || p[j] == '.'));
if (j + 1 < p.length() && p[j + 1] == '*') {
dp[i][j] = dp[i][j + 2] || first_match && dp[i + 1][j];
}
else {
dp[i][j] = first_match && dp[i + 1][j + 1];
}
}
}
return dp[0][0];
}
};