Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
49 lines (42 sloc) 1.21 KB
problem:
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
--------------------------------------------------------------
solution:
//正则表达式的匹配问题,动态规划的思想用递归实现
//因为'*'号的连续性,所以每次考虑p+1是否是'*'来将问题逐步缩小。
bool isMatch(const char *s, const char *p)
{
if(*p == '\0')
return *s == '\0';
if(*(p + 1) != '*')
{
if(*p == *s || ((*p) == '.' && (*s) != '\0'))
return isMatch(s + 1, p + 1);
return false;
}
else
{
while(*p == *s || ((*p) == '.' && (*s) != '\0')) //分别遍历"*"代表1个到若干个字符时是否match
{
if(isMatch(s, p + 2))
{
return true;
}
s++;
}
return isMatch(s, p + 2); // "*"代表0个字符时是否match
}
}