您的位置:首页 > 其它

Regular Expression Matching

2015-06-29 03:19 344 查看
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


class Solution {
public:
bool isMatch(string s, string p) {
int m = s.length();
int n = p.length();

bool buf[m+1][n+1];
buf[0][0] = true;
for (int i = 1; i <= m; i++)
{
buf[i][0] = false;
}
for (int i = 1; i <= n; i++)
{
if (p[i-1] == '*' && buf[0][i-2])
{
buf[0][i] = true;
}
else
{
buf[0][i] = false;
}
}

for (int i = 1; i <= m; i++)
{
for (int j = 1; j <= n; j++)
{
if (s[i-1] == p[j-1] || p[j-1] == '.')
{
if (buf[i-1][j-1])
{
buf[i][j] = true;
}
else
{
buf[i][j] = false;
}
}
else if (p[j-1] == '*')
{
buf[i][j] = buf[i][j-1] || buf[i][j-2] || ((buf[i-1][j-1] || buf[i-1][j]) && (p[j-2] == s[i-1] || p[j-2] == '.'));
}
else
{
buf[i][j] = false;
}
}
}

return buf[m]
;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: