您的位置:首页 > 编程语言 > C#

LeetCode Online Judge 题目C# 练习 - Wildcard Matching

2012-10-23 04:40 405 查看
Implement wildcard pattern matching with support for '?' and '*'.

'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).

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", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false

public static bool WildcardMatching(string s, string p)
{
return WildcardMathchingHepler(s, 0, p, 0);
}

public static bool WildcardMathchingHepler(string s, int i, string p, int j)
{
if (i == s.Length)
{
if (j == p.Length)
return true;
else if (p[j] == '*')
return WildcardMathchingHepler(s, i, p, j + 1);
else
return false;
}
else
{
if (j == p.Length)
return false;
else if (p[j] == '?' || (s[i] == p[j]))
return WildcardMathchingHepler(s, i + 1, p, j + 1);
else if (p[j] == '*')
return WildcardMathchingHepler(s, i, p, j + 1) || WildcardMathchingHepler(s, i + 1, p, j);
else
return false;
}
}


代码分析:

  递归。

  

public static bool WildcardMatchingDP(string s, string p)
{
if (p.Length == 0 && s.Length == 0)
return true;
else if (p.Length == 0 && p[0] != '*')
return false;
else if (s.Length == 0)
return false;

int countp = 0;
for (int i = 0; i < p.Length; i++)
{
if (p[i] != '*')
countp++;
}

if (countp > s.Length)
return false;

bool[,] matrix = new bool[p.Length, s.Length];
countp = 0;
for (int i = 0; i < p.Length; i++)
{
if (p[i] != '*')
countp++;
for (int j = 0; j < s.Length; j++)
{
if (i == 0 && j == 0)
{
if (p[i] == '?' || p[i] == '*' || p[i] == s[j])
matrix[i, j] = true;
else
return false;
}
else if (p[i] == '*')
{
if (i - 1 < 0)
matrix[i, j] = true;
else if (j - 1 < 0)
{
if(matrix[i - 1, j] == true)
matrix[i, j] = true;
else
matrix[i, j] = false;
}
else if (matrix[i - 1, j] == true || matrix[i - 1, j - 1] == true || matrix[i, j - 1] == true)
matrix[i, j] = true;
else
matrix[i, j] = false;
}
else if ((p[i] == '?' || p[i] == s[j]) && j + 1 >= countp)
{
if (i - 1 < 0)
matrix[i, j] = false;
else if (j - 1 < 0)
{
if (p[i - 1] == '*' && matrix[i - 1, j] == true)
matrix[i, j] = true;
else
matrix[i, j] = false;
}
else if (matrix[i - 1, j - 1] == true && p[i - 1] != '*')
matrix[i, j] = true;
else if (p[i - 1] == '*' && matrix[i - 1, j] == true)
{
if (i - 2 < 0 || j - 1 < 0)
matrix[i, j] = true;
else
matrix[i, j] = matrix[i - 2, j - 1];
}
else
matrix[i, j] = false;
}
else
{
matrix[i, j] = false;
}
}
}

return matrix[p.Length - 1, s.Length - 1];
}


代码分析:

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