LeetCode Regular Expression Matching
来源:互联网 发布:在vb中chr是什么意思 编辑:程序博客网 时间:2024/06/03 07:05
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
思路一:最先想到的是直接进行处理,处理各种可能出现的状况。这样实现起来编程难度较大,逻辑清晰也蛮难的,很难一次性bug free思路二:通过分析不难发现,判别是否匹配实际上是一种状态的转换,然后就联想到了动态规划。使用动态规划之前,我们需要理清所求解问题的动态方程:
初始条件:dp[0][0] = true; dp[i][0] = false, i < s.length+1;dp[0][i] = i> 1 && p[i-1] == '*' && p[0][i-2];
动态方程:if p[j-1] == '*' then p[i][j] = p[i][j-2]&&(p[j-2] == '.' || p[i-2] == s[i-1]) && p[i-1][j];
else then p[i][j] = p[i-1][j-1] && (s[i-1] == p[j-1] || p[j-1] == '.');
代码如下:
class Solution {public: bool isMatch(string s, string p) { int sLen = s.length(),pLen = p.length(); bool dp[sLen+1][pLen+1]; int i,j; for(i=0;i<sLen+1;i++) for(j=0;j<pLen+1;j++) { dp[i][j] = false; } dp[0][0] = true; for(i=1;i<sLen+1;i++) dp[i][0] = false; for(i=1;i<pLen+1;i++) dp[0][i] = i>1&& p[i-1] == '*' && dp[0][i-2]; for(i=1;i<sLen+1;i++) { for(j=1;j<pLen+1;j++) { if(p[j-1] == '*') { dp[i][j] = dp[i][j-2] || (p[j-2] == '.' || s[i-1] == p[j-2])&&dp[i-1][j]; } else { dp[i][j] = dp[i-1][j-1] && (s[i-1] == p[j-1] || p[j-1] == '.'); } } } return dp[sLen][pLen]; }};
动态规划真是个好东西
0 0
- LeetCode: Regular Expression Matching
- LeetCode: Regular Expression Matching
- leetcode Regular Expression Matching
- [Leetcode] Regular Expression Matching
- [LeetCode]Regular Expression Matching
- LeetCode-Regular Expression Matching
- Regular Expression Matching LeetCode
- LeetCode | Regular Expression Matching
- LeetCode: Regular Expression Matching
- Leetcode: Regular Expression Matching
- [LeetCode] Regular Expression matching
- [LeetCode] Regular Expression Matching
- LeetCode Regular Expression Matching
- leetcode Regular Expression Matching
- leetcode: Regular Expression Matching
- LeetCode Regular Expression Matching
- Leetcode: Regular Expression Matching
- leetcode:Regular Expression Matching
- wamp上配置虚拟主机
- 温习:装饰者模式
- 解密随机数生成器
- 谁前端比较好,帮我看看
- [笔记]《Linux内核设计与实现》第四章进程调度
- LeetCode Regular Expression Matching
- 利用JQuery实现web页面中table导出excel的功能
- 推荐几本实用的书
- SQL SERVER 复制死锁解决方法
- 如何在Kubernetes中暴露服务访问
- pbpaste & pbcopy in Mac OS X (or: Terminal + Clipboard = Fun!)
- iso checksum 文件使用
- 通过ThoughtWorks.QRCode和ZXing识别二维码
- 欢迎使用CSDN-markdown编辑器