您的位置:首页 > 其它

leetcode Wildcard Matching

2014-08-29 15:24 232 查看
先把题目放上来

'?' 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

自己用了两种方法做了这道题,无奈自己实力太差,两次都未能AC,第一次用到的是递归的思路,可是超时了,第二次选择了用动态规划的方法,同样未能AC,主要原因是空间超了,路漫漫其修远兮,吾将上下而求索,以此来勉(qi)励(pian)自己。

上代码:

bool isMatch(const char *s, const char *p) {
if (*p == '\0')
{
return *s == '\0';
}
if (*s == '\0')
{
return true;
}
if (*(p + 1) == '\0')
{
if (*p == '*')
{
return true;
}
else if (*p == '?')
{
return *(s + 1) == '\0';
}
else
{
return *(s + 1) == '\0' && *p == *s;
}
}
if (*p == '?')
{
return isMatch(s + 1, p + 1);
}
else if (*p == '*')

{
for (int i = 0; i < strlen(s); i++)
{
if (isMatch(s + i, p + 1))
{
return true;
}
}
return false;
}
else
{
if (*p != *s)
{
return false;
}
else
{
return isMatch(s + 1, p + 1);
}
}
}

动态规划:
bool isMatch(const char *s, const char *p)
{
const int m = strlen(s);
const int n = strlen(p);
vector<vector<bool>> f(n + 1, vector<bool>(n + 1, false));
for (int i = 0; i <= n; i++)
{
f[i][0] = true;
}
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
if (p[i - 1] == '?')
{
f[i][j] = f[i - 1][j - 1];
}
else if (p[i - 1] == s[j - 1])
{
f[i][j] = f[i - 1][j - 1];
}
else if (p[i - 1] == '*')
{
if (i != 1)
{
int k;
for (k = 1; k <= m; k++)
{
if (f[i - 1][k])
{
break;
}
}
for (int t = k; t <= m; t++)
{
f[i][t] = true;
}
break;
}
else
{
for (int k = 1; k <= m; k++)
{
f[1][k] = true;
}
}
}
else
{
return false;
}
}
}
return f
[m];
}

注意上面两个都是未能AC的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: