[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.

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 };

 

目录
相关文章
|
C++ Python 算法
leetcode 10 Regular Expression Matching(简单正则表达式匹配)
最近代码写的少了,而leetcode一直想做一个python,c/c++解题报告的专题,c/c++一直是我非常喜欢的,c语言编程练习的重要性体现在linux内核编程以及一些大公司算法上机的要求,python主要为了后序转型数据分析和机器学习,所以今天来做一个难度为hard 的简单正则表达式匹配。
1358 0
LeetCode - 10. Regular Expression Matching
10. Regular Expression Matching Problem's Link  ---------------------------------------------------------------------------- Mean:  给定一个串s和一个自动机p(模糊字符只含有'.
968 0
|
5月前
|
Unix Shell Linux
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
本文提供了几个Linux shell脚本编程问题的解决方案,包括转置文件内容、统计词频、验证有效电话号码和提取文件的第十行,每个问题都给出了至少一种实现方法。
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
|
6月前
|
搜索推荐 索引 Python
【Leetcode刷题Python】牛客. 数组中未出现的最小正整数
本文介绍了牛客网题目"数组中未出现的最小正整数"的解法,提供了一种满足O(n)时间复杂度和O(1)空间复杂度要求的原地排序算法,并给出了Python实现代码。
140 2