leetcode——10.正则表达式匹配

class Solution(object):
    def isMatch(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: bool
        """
        #'.' 匹配任意单个字符
        #'*' 匹配零个或多个前面的那一个元素
        memo=dict()#创建空字典
        def dp(i,j):
            if (i,j) in memo:
                return memo[(i,j)]
            if j==len(p):
                return i==len(s)
            first=i<len(s) and p[j] in {s[i],'.'}
            if j<=len(p)-2 and p[j+1]=='*':
                ans=dp(i,j+2) or( first and dp(i+1,j))
            else:
                ans=first and dp(i+1,j+1)
            memo[(i,j)]=ans
            return ans
        return dp(0,0)
执行用时 :48 ms, 在所有 python3 提交中击败了98.77%的用户
内存消耗 :14 MB, 在所有 python3 提交中击败了5.04%的用户
 
这道题在我现在看来还是很难的,答案也是看来好几遍才懂。
幸亏看了公众号labuladong的关于这道题的算法分析,才让我豁然开朗,真的好牛逼哦。
 
加油啊,在动态规划的道路上扎根。
 
                                                                       ——2019.10.17
 

时隔这么久,还是不会。
难受。
public boolean isMatch(String s, String p) {
        //动态规划
        int m = s.length();
        int n = p.length();
        boolean[][] dp = new boolean[m+1][n+1];
        dp[0][0] = true;
        for(int i = 0;i<=m;i++){
            for(int j = 1;j<=n;j++){
                if(p.charAt(j-1) == '*'){
                    dp[i][j] = dp[i][j-2];
                    if(matches(s,p,i,j-1)){
                        dp[i][j] = dp[i][j] || dp[i-1][j];
                    }
                }else{
                    if(matches(s,p,i,j)){
                        dp[i][j] = dp[i-1][j-1];
                    }
                }
            }
        }
        return dp[m][n];
    }

    private 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);
    }

 动态规划啊,咋就不会做呢,稍微难一点就开始不会了。

人生艰难。

——2020.7.7

 
 
 
我的前方是万里征途,星辰大海!!
原文地址:https://www.cnblogs.com/taoyuxin/p/11690015.html