zoukankan      html  css  js  c++  java
  • LeetCode #10 中等题 (实现简单正则匹配)

    题目:实现简单正则匹配,除了小写字母就只有 "." 和 "*" 了。

    题解: 我用的记忆化搜索,直接暴力搜索太蠢了,记录一下已经计算过得 s[i] 与 p[j] 的匹配情况,如果要用话看是否已经处理过了再决定要不要算就好了,为了省内存记忆化的数组动态开了= =

    class Solution {
    public:
        int **dp;
        int n,m;
        bool dfs(int i, int j, const string& s, const string& p){
            if (dp[i][j] != 0) return dp[i][j] == 1;
            bool ans = false;
            if (j == m){
                ans = i == n;
            } else{
                bool match = (i < n && (p[j] == s[i] || p[j] == '.'));
    
                if (j + 1 < m && p[j + 1] == '*'){
                    ans = (dfs(i, j + 2, s, p) || match && dfs(i + 1, j, s, p));
                } else {
                    ans = match && dfs(i + 1, j + 1, s, p);
                }
            }
            dp[i][j] = ans ? 1 : -1;
            return ans;
        }
        
        bool isMatch(string s, string p) {
            n = (int)s.size(),m = (int)p.size();
            dp = new int*[n + 1];
            for (int i = 0; i < n + 1; ++i){
                dp[i] = new int[m + 1];
                for (int j = 0; j < m + 1; ++j)
                    dp[i][j] = 0;
            }
            bool res = dfs(0, 0, s, p);
            delete[] dp;
            return res;
        }
    };
  • 相关阅读:
    行转列函数listagg() WITHIN GROUP ()
    位图索引
    windows 杀掉进程
    vue 实践(过滤器)
    vue 总结
    vue v-show v-if 的使用
    vue v-for 绑定数据
    vue v-model实现数据的双向绑定
    vue .stop .self .capture .prevent 阻止冒泡
    vue v-on v-text 的运用
  • 原文地址:https://www.cnblogs.com/error408/p/11645225.html
Copyright © 2011-2022 走看看