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
//字符串和正则表达式,是否匹配
算法
DFS
O(n!)
class Solution {
public:
bool isMatch(string s, string p) {
if(s.length() == 0){
if(p.length() & 1) return false;
else{
for(int i = 1; i < p.length(); i += 2) if(p[i] != '*') return false;
return true;
}
}
if(p.length() == 0) return false;
if(p.length() > 1 && p[1] == '*'){
if(p[0] == '.' || s[0] == p[0]) return isMatch(s.substr(1), p) || isMatch(s, p.substr(2));
else return isMatch(s, p.substr(2));
}
else{
if(p[0] == '.' || p[0] == s[0]) return isMatch(s.substr(1), p.substr(1));
else return false;
}
}
};
算法
DF
偷懒的方法是直接用语言自带的正则实现。(Python 又是一句话 =w=)
用 DFS 的方法
可以用 DP 的方法
用数组 DP :dp[i][j] 表示 s[0..i] 和 p[0..j] 是否 match,当 p[j] != ‘‘,b[i + 1][j + 1] = b[i][j] && s[i] == p[j] ,当 p[j] == ‘’ 要再分类讨论,具体可以参考 DP C++,还可以压缩下把 dp 降成一维:参考这里
用记忆化,就是把算过的结果保存下来,下次就不用再算了