您的位置:首页 > 其它

LeetCode--wildcard-matching

2018-01-17 22:54 393 查看
题目: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

方法一:

这道题通配符匹配问题还是小有难度的,这道里用了贪婪算法Greedy Alogrithm来解,由于有特殊字符*和?,其中?能代替任何字符,*能代替任何字符串,那么我们需要定义几个额外的指针,其中scur和pcur分别指向当前遍历到的字符,再定义pstar指向p中最后一个*的位置,sstar指向此时对应的s的位置,具体算法如下:

- 定义scur, pcur, sstar, pstar

- 如果*scur存在

  - 如果*scur等于*pcur或者*pcur为 '?',则scur和pcur都自增1

  - 如果*pcur为'*',则pstar指向pcur位置,pcur自增1,且sstar指向scur

  - 如果pstar存在,则pcur指向pstar的下一个位置,scur指向sstar自增1后的位置

- 如果pcur为'*',则pcur自增1

- 若*pcur存在,返回False,若不存在,返回True

bool isMatch(char *s, char *p) {
char *scur = s, *pcur = p, *sstar = NULL, *pstar = NULL;
while (*scur) {
if (*scur == *pcur || *pcur == '?') {
++scur;
++pcur;
} else if (*pcur == '*') {
pstar = pcur++;
sstar = scur;
} else if (pstar) {
pcur = pstar + 1;
scur = ++sstar;
} else return false;
}
while (*pcur == '*') ++pcur;
return !*pcur;
}

方法二:动态规划
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 = 1; i <= n; ++i) {
if (p[i - 1] == '*') dp[0][i] = dp[0][i - 1];
//s第一个字符的匹配情况,方便后面的递推公式
}
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (p[j - 1] == '*') {
dp[i][j] = dp[i - 1][j] || dp[i][j - 1];
//p中前一个字符为'*'时,对应s中的字符为‘’时,dp[i][j]由dp[i-1][j]决定,即j++
//当这个'*'对应s中的任一字符串时,dp[i][j]由dp[i][j - 1],即i++
//有点像子字符串匹配问题
} else {
dp[i][j] = (s[i - 1] == p[j - 1] || p[j - 1] == '?') && dp[i - 1][j - 1];
}
}
}
return dp[m]
;
}
};

转自:https://www.cnblogs.com/grandyang/p/4401196.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: