add: 0010

This commit is contained in:
Eatswap 2023-02-28 21:11:08 +08:00
parent e4d15ecf06
commit acd093331d
Signed by: Eatswap
GPG Key ID: BE661106A1F3FA0B
1 changed files with 50 additions and 0 deletions

50
cpp/more/0010.cpp Normal file
View File

@ -0,0 +1,50 @@
#include <string>
#include <cstring>
/**
* 10. Regular Expression Matching
*
* Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where:
*
* '.' Matches any single character.
* '*' Matches zero or more of the preceding element.
* The matching should cover the entire input string (not partial).
*/
class Solution {
private:
int dp[21][21];
int sl;
bool f(const char* s, const char* p, int sd = 0, int pd = 0) {
// Look at table
if (dp[sd][pd] >= 0)
return dp[sd][pd];
// Terminated regex?
if (!p[pd])
return dp[sd][pd] = !s[sd];
// Empty s?
if (!s[sd])
return dp[sd][pd] = (!p[pd]) || (p[pd + 1] == '*' && f(s, p, sd, pd + 2));
// Look ahead
if (p[pd + 1] != '*')
return dp[sd][pd] = (p[pd] == '.' || p[pd] == s[sd]) && f(s, p, sd + 1, pd + 1);
// Contains *
// Match 0 or all chars.
for (int nsd = sd; nsd <= this->sl;) {
if (f(s, p, nsd, pd + 2))
return dp[sd][pd] = true;
if (p[pd] != s[nsd++] && p[pd] != '.')
break;
}
return dp[sd][pd] = false;
}
public:
bool isMatch(const std::string& s, const std::string& p) {
std::memset(this->dp, -1, sizeof this->dp);
this->sl = s.length();
return f(s.c_str(), p.c_str());
}
};