Wildcard Matching
Given an input string (s) and a pattern §, 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).
Note:
- s could be empty and contains only lowercase letters a-z.
- p could be empty and contains only lowercase letters a-z, and characters like ? or *.
Example 1:
Input:
s = “aa”
p = “a”
Output: false
Explanation: “a” does not match the entire string “aa”.
Example 2:
Input:
s = “aa”
p = ""
Output: true
Explanation: '’ matches any sequence.
Example 3:
Input:
s = “cb”
p = “?a”
Output: false
Explanation: ‘?’ matches ‘c’, but the second letter is ‘a’, which does not match ‘b’.
Example 4:
Input:
s = “adceb”
p = “ab”
Output: true
Explanation: The first ‘’ matches the empty sequence, while the second '’ matches the substring “dce”.
Example 5:
Input:
s = “acdcb”
p = “a*c?b”
Output: false
解析
?可以匹配任意单个字符,*匹配任意长度的字符。判断p是否可以匹配s。
解法1:动态规划
使用动态规划求解:
使用一个二维数组dp[s.size+1][p.size+1],dp[i][j]表示字符串s中0-i的字符能否匹配p中0-j的字符,并初始dp[0][0]=1;
当p[j]=s[i]或者p[j] =‘?’时,dp[i][j] = dp[i-1][j-1];
当p[j]=’*'时,可以匹配0个字符,dp[i][j] = dp[i-1][j],可以匹配1个字符,dp[i][j] = dp[i-1][j-1],所以
dp[i][j] = dp[i-1][j] || dp[i-1][j-1] ||…|| dp[i-1][0].
由于dp[i][j-1] = dp[i-1][j-1] || dp[i-1][j-2] ||…|| dp[i-1][0].
得到dp[i][j] = dp[i-1][j] || dp[i][j-1].
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];
}
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];
else
dp[i][j] = (s[i - 1] == p[j - 1] || p[j - 1] == '?') && dp[i - 1][j - 1];
}
}
return dp[m][n];
}
};
解法2
使用四个指针来记录位置,分别为
pcur:p字符串当前位置
scur:s字符串当前位置
pstar:最后一个*的位置
sstar:对应与pstar的s的位置
初始化pcur=scur=0,pstar=sstar=-1;
迭代过程如下:
当scur<s.size()时
- 如果s[scur]=p[pcur]或者p[pcur]=?,pcur++,scur++;
- 如果p[pcur]=‘*’,pstar=pcur,pcur++,sstar=scur;
- 如果pstar存在,pcur=pstar+1,sstar++,scur=sstar;
如果p[pcur]=’*’,pcur++;
如果pcur=p.size,返回true。
class Solution {
public:
bool isMatch(string s, string p) {
int sstar=-1;
int pstar=-1;
int pindex = 0,sindex=0;
int size = s.size();
while (sindex<size){
if ((p[pindex]=='?')||(p[pindex]==s[sindex])){
sindex ++;
pindex ++;
}
else if (p[pindex]=='*'){
pstar = pindex;
pindex ++;
sstar = sindex;
}
else if (pstar != -1){
pindex = pstar+1;
sstar ++;
sindex = sstar;
}
else
return false;
}
while (p[pindex]=='*'){pindex++;}
return pindex==p.size();
}
};
参考
https://www.cnblogs.com/yuzhangcmu/p/4116153.html
https://www.cnblogs.com/grandyang/p/4401196.html