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));
        }
    };
  • 相关阅读:
    3288 积木大赛
    3284 疯狂的黄大神
    1531 山峰
    1018 单词接龙
    1432 总数统计
    1507 酒厂选址
    1063 合并果子
    几个sort不能过的题目
    poj 2245 Lotto
    求两圆相交面积模板
  • 原文地址:https://www.cnblogs.com/JTechRoad/p/9051760.html
Copyright © 2011-2022 走看看