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:boolisMatch(constchar*s,constchar*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
Basic Idea:
如果不考虑 * 的情况,我们实际上只需要做一个 linear scan 就可以完成匹配,因为 s 和 p 在这种情况下他们的每个字母都必须一一对应。然而当我们加入对 * 的考虑之后,现在就存在了一个需要考虑一个 * 要匹配几次的问题。比如,对于 abbba 和 ab*a 的情况,b* 匹配了尽可能多的字符,直到最后一个 a 之前的所有 b 都匹配了。而对于 abbba 和 ab*ba,* 就只能匹配两个 b。
上面的情况说明会出现s和p两string之间不同位置对应进行匹配的情况,于是我们想到使用 dp 的思路求解。Induction Rule 和 Base Case 如下: