zoukankan      html  css  js  c++  java
  • [LeetCode] Regular Expression Matching

    This problem has a typical solution using Dynamic Programming. We define the state P[i][j] to be true if s[0..i) matches p[0..j) and false otherwise. Then the state equations are:

    1. P[i][j] = P[i - 1][j - 1], if p[j - 1] != '*' && (s[i - 1] == p[j - 1] || p[j - 1] == '.');
    2. P[i][j] = P[i][j - 2], if p[j - 1] == '*' and the pattern repeats for 0 times;
    3. P[i][j] = P[i - 1][j] && (s[i - 1] == p[j - 2] || p[j - 2] == '.'), if p[j - 1] == '*' and the pattern repeats for at least 1 times.

    Putting these together, we will have the following code.

     1 class Solution {
     2 public:
     3     bool isMatch(string s, string p) {
     4         int m = s.length(), n = p.length();
     5         vector<vector<bool> > dp(m + 1, vector<bool> (n + 1, false));
     6         dp[0][0] = true;
     7         for (int i = 0; i <= m; i++)
     8             for (int j = 1; j <= n; j++)
     9                 if (p[j - 1] == '*')
    10                     dp[i][j] = dp[i][j - 2] || (i > 0 && (s[i - 1] == p[j - 2] || p[j - 2] == '.') && dp[i - 1][j]);
    11                 else dp[i][j] = i > 0 && dp[i - 1][j - 1] && (s[i - 1] == p[j - 1] || p[j - 1] == '.');
    12         return dp[m][n];
    13     }
    14 };
  • 相关阅读:
    mtk lk阶段的lcm流程
    MTK touchscreen 流程
    MTK DDR调试
    增加,删除GMS包
    最大最小背光亮度修改
    HDMI 8193 配置
    mtk6737t摄像头配置文件的编译
    camera调试命令
    Linux 终端显示 Git 当前所在分支
    ubuntu系统,关于源(source)的配置
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4623211.html
Copyright © 2011-2022 走看看