给你一个字符串 s 和一个字符规律 p,请你来实现一个支持 ‘.’ 和 ‘’ 的正则表达式匹配。
‘.’ 匹配任意单个字符
'’ 匹配零个或多个前面的那一个元素
‘?’ 匹配一个或多个前面的那一个元素
所谓匹配,是要涵盖 整个 字符串 s的,而不是部分字符串。
递归算法
public static bool myfun(string s, string p)
{
if (p.Length == 0) return s.Length == 0;
bool match=false;
if(s.Length>0)
match = s[0] == p[0] || p[0] == '.';
string strA = "";
string strB = "";
if (p.Length >= 2 && p[1] == '*')
{
strB = p.Substring(2);
if (s.Length > 1) strA = s.Substring(1);
if (match)
{
return myfun(s, strB) || myfun(strA, p);
}
else
return myfun(s, strB);
}
if (p.Length >= 2 && p[1] == '?')
{
if (!match) return false;
else
{
if (s.Length > 1) strA = s.Substring(1);
strB = p.Replace('?', '*').Substring(0,2);
strB += p.Substring(2);
return myfun(strA, strB);
}
}
else
{
if (!match) return false;
else
{
if (p.Length > 1) strB = p.Substring(1);
if (s.Length > 1) strA = s.Substring(1);
return myfun(strA, strB);
}
}
要点说明
1.当p下一字符不是特殊字符且match则递归myfun(s-1,p-1)
2.懂得都懂,不解释了
动态规划算法
public static bool myfun(string s,string p)
{
int m = s.Length+1, n = p.Length+1;
bool[,] dp = new bool[m, n];
dp[0, 0] = true;
for (int i = 1; i < m; i++)
{
dp[i, 0] = false;
}
for (int i = 0; i < n-1; i++)
{
if (p[i] == '*') dp[0, i+1] = dp[0, i - 1];
else dp[0, i+1] = false;
}
for (int i = 0; i < m-1; i++)
{
for (int j = 0; j < n-1; j++)
{
if (p[j] == s[i] || p[j] == '.') dp[i + 1, j + 1] = dp[i, j];
if (p[j] == '*')
{
if (p[j - 1] == s[i] || p[j-1] == '.') dp[i + 1, j + 1] = dp[i + 1, j - 1] || dp[i, j + 1];
else dp[i + 1, j + 1] = dp[i + 1, j - 1];
}
if (p[j] == '?')
{
if (p[j - 1] == s[i] || p[j - 1] == '.') dp[i + 1, j + 1] = dp[i, j - 1] || dp[i, j + 1];
else
dp[i + 1, j + 1] = false;
}
}
}
return dp[m-1, n-1];
动态规划虽然能写出来,但理解暂时不到位
总的来说就是填充数组
难在很难从抽象问题具体化