LeetCode: Regular Expression Matching
来源:互联网 发布:js实现页面加载效果 编辑:程序博客网 时间:2024/05/17 03:34
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[i][j]表示字串 s[i...len(s)], p[j...len(p)] 是否可以匹配。http://blog.csdn.net/hopeztm/article/details/7992253
状态转移方程如下:
dp[i][j] =
c1. p[j+1] != '*'时 if s[i] == p[j] dp[i][j] = dp[i+1][j+1]
else dp[i][j] = false
c2 p[j+1] == '*'时 (这个情况下,要扩展 *, dp[i][j] 从拓展的情况下,选择一个是真的结果)
if( s[i] == p[j] || p[j] == '.' && (*s) != 0) 当s[i] 和 p[j] 一样的时候,例如 aba, a*b这个时候,i = 0, j = 0, 自然可以匹配a a
如果p[j] == . 因为他可以匹配任何字符,所以和相等关系有基本一样的方式。
并且每一步匹配都要递增 i 的值,如果有成立的,则返回true,否则到匹配终了,返回通配符匹配完成后的结果。
class Solution {public: bool isMatch(const char *s, const char *p) { // Start typing your C/C++ solution below // DO NOT write int main() function if (*p == '\0') return *s == '\0'; if (*(p+1) == '*') // 模式串的下一个字符是'*' { while(*p == *s || (*p == '.' && *s != '\0')) { //字符串与模式串匹配0/1/2...个字符的情况 if (isMatch(s++, p+2)) return true; } // 字符串与模式串不能匹配 return isMatch(s, p+2); } else { if (*p == *s || (*p == '.' && *s != '\0')) return isMatch(s+1, p+1); return false; } }};
- 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
- MFC连接数据库方法
- 二维指针,二维数组,以及指向数组的指针的相关问题
- uestc 1650 Electric System Restore(中位数定理?)
- 用C++进行简单的文件I/O操作
- 关于document.cookie的使用
- LeetCode: Regular Expression Matching
- C#获取文件后缀名
- c++文件打开和关闭
- vb三点求圆,多点求外接圆。
- 栈和队列
- Myeclipse下web项目改名,tomcat下不变的问题
- mysql order by 1,2,3
- ArcGIS for iOS 开发系列(2) – 开发环境配置
- 微软献给程序员的大片-娱乐