题目:
Regular Expression Matching
'.' 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
分析:
1、isMath("abcd",".*")->true
因为根据定义,exp为".*"的话,'*'前一个字符是'.',所以可以表示任意数量的'.',那么exp当然可以是"....",这与"abcd"是匹配的。
isMath("",".*")->true
注意:空字符串可以和 ".*" 匹配。
2、用在递归中,用记忆法消除重复计算。注意要使用二维数组代替哈希表作为缓存,因为二维数组的读取速度更快。
class Solution {
public:
bool isMatch(string s, string p) {
vector<vector<int>> cache(s.size() + 1, vector<int>(p.size() + 1, -1));
return isMatch(s, p, 0, 0, cache);
}
bool isMatch(const string &s, const string &e, int si, int ei, vector<vector<int>> &cache)
{
if (cache[si][ei] != -1)
return cache[si][ei];
int esize = e.size(), ssize = s.size();
if (ei == esize)
{
cache[si][ei] = si == ssize ? 1 : 0;
return si == ssize;
}
if (ei<=esize-2 && e[ei + 1] == '*')
{
while ((si != ssize && e[ei] == '.') || s[si] == e[ei])
{
if (isMatch(s, e, si, ei + 2, cache))
{
cache[si][ei] = 1;
return true;
}
++si;
}
return isMatch(s, e, si, ei + 2, cache);
}
else if ((si != ssize && e[ei] == '.') || s[si] == e[ei])
{
return isMatch(s, e, si + 1, ei + 1, cache);
}
cache[si][ei] = 0;
return false;
}
};