Leetcode DP4 Wildcard Matching

2018-09-18  本文已影响0人  golfgang

太难了,没做出来

给个例子自己体会:


dp table

代码:https://blog.csdn.net/ymzmdx/article/details/44709273

class Solution {
public:
   bool isMatch(string s, string p) {
        int len_s = s.size();
        int len_p = p.size();
        bool dp[500][500] = {{false}};  //用于记录每个子问题的解
        int lens = 0;
        if(len_p != 0){ 
            for(int i = 0;i < len_p;i++)
                if(p[i] != '*') lens++;
        }
        if(lens > len_s) return false;
        dp[0][0] = true;    //两个串都是空的for
        for(int j = 1;j <= len_p;j++){
            if(dp[0][j-1] && p[j-1] == '*') dp[0][j] = true; 
            for(int i = 1;i <= len_s;i++){
                if(p[j-1] == '*') dp[i][j] = dp[i][j-1] || dp[i-1][j];
                else if(p[j-1] == '?'||p[j-1] == s[i-1]) dp[i][j] = dp[i-1][j-1];
                else dp[i][j] = false;
            }
        }
        return dp[len_s][len_p];
        }
};
上一篇 下一篇

猜你喜欢

热点阅读