一.问题描述
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") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
注:这个题目还是需要认真审题的,'c*'是一体的,代表0个或多个c;'.*'则代表0个或多个任意字符。
二.代码编写
这一题需要考虑的情况很多,我在自行设计算法的时候没考虑清楚,提交的时候跳出来的特殊情况导致了我的整个算法都得推翻重来。其中,'.*'的匹配情况完全没办法通过打补丁来解决。
多次推导重来之后再网上搜索了该题的解法。解法基本上就是递归和dp两种思想,但是递归解法会导致TLE。
三.算法思想
递归思想:参考http://pengbos.com/algorithms/leetcode-regular-expression-matching-solution
String match, and it is a typical DP problem.
create a two dimension table dp[s.length()+1][p.length()+1]
so dp[i][j] means whether string [0, i-1] matches pattern [0, j-1]
and dp[i+1][j+1] means whether string [0, i] matches pattern [0, j]