Leetcode10. Regular Expression Matching DP问题

参考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];
	}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值