zoukankan      html  css  js  c++  java
  • 44. Wildcard Matching

    Recurision, TLE.

    class Solution {
    public:
        bool isMatch(string s, string p) {
            int sl = s.length(), pl = p.length();
            int i = 0, j = 0;
            if (pl == 0)    return sl == 0;
            if (p[j] == '*') {
                while (p[j+1] == '*')   j++;
                for (int k = 0; k <= sl; k++)
                    if (isMatch(s.substr(k), p.substr(j+1)))
                        return true;
                return false;
            }
            if (sl > 0 && (s[0] == p[0] || p[0] == '?'))
                return isMatch(s.substr(1), p.substr(1));
            return false;
        }
    };

    DP:

    class Solution {
    public:
        bool isMatch(string s, string p) {
            int sl = s.length(), pl = p.length();
            vector<vector<bool>> dp(sl+1, vector<bool>(pl+1, false));
            dp[0][0] = true;
            for (int j = 1; j <= pl; j++) {
                if (p[j-1] == '*')  dp[0][j] = true;
                else break;
            }
            for (int i = 1; i <= sl; i++)
                for (int j = 1; j <= pl; j++) {
                    if (p[j-1] == '*') {
                        for (int k = i; k >= 0; k--) {
                            if (dp[k][j-1]) {
                                dp[i][j] = true;
                                break;
                            }
                        }
                    }
                    else if (s[i-1] == p[j-1] || p[j-1] == '?') {
                        dp[i][j] = dp[i-1][j-1];
                    }
                }
            return dp[sl][pl];
        }
    };
  • 相关阅读:
    ios本地推送
    ios BUG
    性能优化
    数据结构设计
    代码的可维护性
    NSMutalbleDictionary
    NSDictionary
    NSMutableArray
    java 容器
    Java bug
  • 原文地址:https://www.cnblogs.com/JTechRoad/p/9070187.html
Copyright © 2011-2022 走看看