leetcode题解c++ | 10. Regular Expression Matching
来源:互联网 发布:淘宝图片一般像素多少 编辑:程序博客网 时间:2024/06/05 11:26
题目:https://leetcode.com/problems/regular-expression-matching/#/description
Implement regular expression matching with support for '.'
and '*'
.
'.' Matches any single character.'*' Matches zero or more of the preceding element.The matching should cover the entire input string (not partial).The function prototype should be:bool isMatch(const char *s, const char *p)Some examples:isMatch("aa","a") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "a*") → trueisMatch("aa", ".*") → trueisMatch("ab", ".*") → trueisMatch("aab", "c*a*b") → true
分析:刚开始想直接匹配,但对于带*的,就很难做判断。想了很久才想通dp来做比较简单
f[i][j]: s[0..i-1] 是否匹配p[0..j-1]
if p[j - 1] != '*'
f[i][j] = f[i-1][j-1]&& (p[j-1]=='.'||s[i-1]==p[j-1])
if p[j - 1] == '*', 设 p[j - 2] 为 x
1) "x*" 重复0次:f[i][j] = f[i][j - 2]
2)"x*" 重复1次以上:f[i][j] = f[i-1][j] && (p[j-2]=='.'||s[i-1]==p[j-2])
注意这里只需要转移重复一次的情况,而不需要枚举重复的次数。还有初始化需要分类,这个想一下也很容易想通。
c++实现:bool isMatch(string s, string p){ int m=s.length(), n=p.length(); bool f[m+1][n+1]; f[0][0] = 1; for(int i=1; i<=m; ++i) f[i][0] = 0; for(int i=1; i<=n; ++i) if(p[i-1]!='*') f[0][i] = 0; else f[0][i] = f[0][i-2]; for(int i=1; i<=m; ++i) for(int j=1; j<=n; ++j) { if(p[j-1]!='*') f[i][j] = f[i-1][j-1]&& (p[j-1]=='.'||s[i-1]==p[j-1]); else f[i][j] = f[i][j-2] || (f[i-1][j]&& (p[j-2]=='.'||s[i-1]==p[j-2])); } return f[m][n];}
0 0
- LeetCode题解--10. Regular Expression Matching
- leetcode题解c++ | 10. Regular Expression Matching
- 10. Regular Expression Matching LeetCode题解
- leetcode题解-10. Regular Expression Matching
- LeetCode题解: Regular Expression Matching
- LeetCode 题解(13):Regular Expression Matching
- leetcode题解||Regular Expression Matching 问题
- LeetCode题解-10-Regular Expression Matching
- Leetcode题解---Regular Expression Matching Java实现
- [LeetCode]10.Regular Expression Matching
- LeetCode --- 10. Regular Expression Matching
- [Leetcode] 10. Regular Expression Matching
- [LeetCode]10.Regular Expression Matching
- [leetcode] 10.Regular Expression Matching
- Leetcode-10.Regular Expression Matching
- leetcode 10. Regular Expression Matching
- leetcode 10. Regular Expression Matching
- Leetcode 10. Regular Expression Matching
- String、StringBuffer和StringBuilder的区别
- Android介绍
- 【软考】算法-插入
- 选择文件后自动上传
- 数据持久化
- leetcode题解c++ | 10. Regular Expression Matching
- 维度建模的基本概念及过程
- 手写代码算法题和智力题
- Android应用开发入门经典学习笔记01--理解Android Activity
- Java中hashCode的作用
- Linux下检查是否安装过某软件包
- C/C++常用头文件及函数汇总
- WINDOWS下APACHE+PHP下载、安装、配置
- Array Partition I