Lintcode154 Regular Expression Matching solution 题解

来源:互联网 发布:大麦盒子软件下载 编辑:程序博客网 时间:2024/06/07 22:57

【题目描述】

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/

作者:程风破浪会有时链接:http://www.jianshu.com/p/32925a05c699來源:简书著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
原创粉丝点击