Lintcode154 Regular Expression Matching solution 题解
来源:互联网 发布:大麦盒子软件下载 编辑:程序博客网 时间:2024/06/07 22:57
作者:程风破浪会有时链接:http://www.jianshu.com/p/32925a05c699來源:简书著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。【题目描述】
Implement regular expression matching with support for'.'and'*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover theentireinput string (not partial).The function prototype should be:bool isMatch(const char *s, const char *p)
实现支持'.'和'*'的正则表达式匹配。
'.'匹配任意一个字母。
'*'匹配零个或者多个前面的元素。
匹配应该覆盖整个输入字符串,而不仅仅是一部分。
需要实现的函数是:bool isMatch(const char *s, const char *p)
【题目链接】
www.lintcode.com/en/problem/regular-expression-matching/
【题目解析】
在这道题中“”表示的是可以取任意多个其之前的字符,比如“a” 就表示“”可以取任意多个“a”,例如0个(“”),1个(“a”),2个(“aa”)...。可以用DP来解决。
match[i][j]表示s中前i个字符能否和p中前j个字符匹配。
初始化:
match[0][0] = true
match[0][j] = (p.charAt(j - 1) == '*' && match[0][j - 2])
即如果p中第j位是“ * ”,则对第j-1位的字符取0个(即第j-1到第j位字符看作“”),所以match[0][j]=match[0][j-2]
状态函数:
如果p中第j位是“ . ”或者p中第j位和s中第i位相同
match[i][j] = match[i - 1][j - 1]
如果p中第j位是“ * ”,则要分情况讨论
1. 如果p中第j-1位和s中第i位不想等并且p中第j-1位不是“.”,则不能用p中j-1位和s中第i位匹配,必须将j-1位消掉,因此“*”取0个之前元素,match[i][j]=match[i][j-2]
2. 如果p中第j-1位和s中第i位想等或者p中第j-1位为“.”,则“*”可以有三种选择
1)“*”取0个之前元素,和1中一样,将第j-1位消掉,让j-2位去和i位匹配(“”),match[i][j]=match[i][j-2]
2)“*”取1个之前元素,让j-1位和i位匹配,match[i][j]=match[i][j-1]
3)“*”取多个之前元素,因为i位一定会被匹配掉,因此看i-1位能否继续匹配,match[i][j]=match[i-1][j]
三种情况有一种为true则match[i][j]为true
【参考答案】
www.jiuzhang.com/solutions/regular-expression-matching/
- Lintcode154 Regular Expression Matching solution 题解
- 题解:Regular Expression Matching
- [LeetCode] Regular Expression Matching, Solution
- LeetCode题解: Regular Expression Matching
- LeetCode 题解(13):Regular Expression Matching
- leetcode题解||Regular Expression Matching 问题
- LeetCode题解--10. Regular Expression Matching
- LeetCode题解-10-Regular Expression Matching
- leetcode题解c++ | 10. Regular Expression Matching
- 10. Regular Expression Matching LeetCode题解
- Leetcode题解---Regular Expression Matching Java实现
- leetcode题解-10. Regular Expression Matching
- 010_LeetCode_10 Regular Expression Matching 题解
- LeetCode题解——10Regular Expression Matching
- LEETCODE 10 Regular Expression Matching (JAVA题解)
- LeetCode: Regular Expression Matching
- LeetCode: Regular Expression Matching
- leetcode Regular Expression Matching
- Lintcode153 Combination Sum II solution 题解
- 三、基本组件(四)深入理解ContentProvider
- 【个人笔记】truncate()
- 多态
- 使用多线程获取大量数据集合中的关键数据
- Lintcode154 Regular Expression Matching solution 题解
- centos7中安装docker
- 有赞.测试团队介绍(转)
- 计算机体系结构--中央处理器
- 接口
- 数据分析之Matplotlib绘图-01
- 数据库部分语句(持续更新)
- 编程 计算π值 毕达哥拉斯三元组 柱状图
- jdk8源码阅读之Serializable