问题描述
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
思路
可以采用DP,backtracking解决,一次匹配一段。本题只涉及'.','*'两个匹配符号。
Code
C语言代码
注意s的++的位置!
|
|
附加通配符匹配:leetcode 44
思路类似,同样注意s的++位置!
递归Code
|
|
然而提交的时候TLE, _(:зゝ∠)_
回溯算法
递归的开销太大,所以考虑了一下回溯算法。
思路
当遇到'*'时,找到p的最近的下一个非'*'字符并标记位置,并且记录s匹配的初始位置。
|
|
当*p与*s不匹配时,如果p的前面存在'*',则进行回溯, p回到startP位置,而s = (++startS)。
Code
总体时间复杂度\(\Theta(s \times p)\)
|
|