Given an input string (s
) and a pattern (p
), implement regular expression matching with support for '.'
and '*'
.
方法一:C语言
bool isMatch(char* s, char* p) {
if(s==NULL || p==NULL)return false;
if(!*p) return !*s;
if(*(p+1)=='*'){
if((*p==*s)||(*s && *p=='.')){
return isMatch(s+1,p+2)||isMatch(s+1,p)||isMatch(s,p+2);
}
else
return isMatch(s,p+2);
}else if((*p==*s)||(*s && *p=='.')){
return isMatch(s+1,p+1);
}
return false;
}
方法二:动态规划C++
class Solution {
public:
bool isMatch(string s, string p)
{
int m = s.size(), n = p.size();
vector<vector<bool>> dp(m + 1, vector<bool>(n + 1, false));
dp[0][0] = true;
for (int i = 0; i <= m; ++i)
{
for (int j = 1; j <= n; ++j)
{
if (j > 1 && p[j - 1] == '*')
{
dp[i][j] = dp[i][j - 2] || (i > 0 && (s[i - 1] == p[j - 2] || p[j - 2] == '.') && dp[i - 1][j]);
}
else {
dp[i][j] = i > 0 && dp[i - 1][j - 1] && (s[i - 1] == p[j - 1] || p[j - 1] == '.');
}
}
}
return dp[m][n];
}
};
完整代码:
#include<iostream>
using namespace std;
bool matchCore(const char* str, const char* pattern);
bool match(const char* str, const char* pattern)
{
if (str == nullptr || pattern == nullptr)
return false;
return matchCore(str, pattern);
}
bool matchCore(const char* str, const char* pattern)
{
if (*str == '\0' && *pattern == '\0')
return true;
if (*str != '\0' && *pattern == '\0')
return false;
if (*(pattern + 1) == '*')
{
if (*pattern == *str || (*pattern == '.' && *str != '\0'))
// 进入有限状态机的下一个状态
return matchCore(str + 1, pattern + 2)
// 继续留在有限状态机的当前状态
|| matchCore(str + 1, pattern)
// 略过一个'*'
|| matchCore(str, pattern + 2);
else
// 略过一个'*'
return matchCore(str, pattern + 2);
}
if (*str == *pattern || (*pattern == '.' && *str != '\0'))
return matchCore(str + 1, pattern + 1);
return false;
}
int main()
{
bool result=match("abc", "ab*c*");
cout << result;
system("pause");
return 0;
}