zoukankan      html  css  js  c++  java
  • 10. Regular Expression Matching

    https://leetcode.com/problems/regular-expression-matching/description/

    DP:

    class Solution {
    public:
        bool isMatch(string s, string p) {
            int m = s.length(), n = p.length();
            vector<vector<bool>> dp(m+1, vector<bool>(n+1, false));
            dp[0][0] = true;
            for (int j = 1; j < n; j++) {
                if (p[j] == '*')
                    dp[0][j+1] = dp[0][j-1];  // we should p[j-1]p[j]
            }
            for (int i = 1; i <= m; i++)
                for (int j = 1; j <= n; j++) {
                    if (s[i-1] == p[j-1] || p[j-1] == '.')
                        dp[i][j] = dp[i-1][j-1];
                    else if (j-1 > 0 && p[j-1] == '*') {
                        if (s[i-1] == p[j-2] || p[j-2] == '.')
                            dp[i][j] = dp[i][j-2] || dp[i-1][j];
                        else
                            dp[i][j] = dp[i][j-2];
                    }
                }
            return dp[m][n];
        }
    };

     recursion

    class Solution {
    public:
        bool isMatch(string s, string p) {
            int m = s.length(), n = p.length();
            if (n == 0) return m == 0;
            bool firstMatch = m > 0 && (s[0] == p[0] || p[0] == '.');
            if (n > 1 && p[1] == '*') {
                if (firstMatch && isMatch(s.substr(1), p))
                    return true;
                return isMatch(s, p.substr(2));
            }
            return firstMatch && isMatch(s.substr(1), p.substr(1));
        }
    };
  • 相关阅读:
    Linux下的MySQL主从同步
    人不能同时在两个地方做猪(Scrum Team)
    memcache安装
    Java开发中的Memcache原理及实现
    linux mv
    nginx
    idea 热部署
    vue watch
    vue入门
    基于vue-cli快速构建
  • 原文地址:https://www.cnblogs.com/JTechRoad/p/9051760.html
Copyright © 2011-2022 走看看