题目描述:
Given an input string (s) and a pattern (p), 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:
scould be empty and contains only lowercase lettersa-z.pcould be empty and contains only lowercase lettersa-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 = "*a*b" 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
外卡匹配, “?”匹配任意一个字符,“*”匹配任意一串字符,包括空字符串。
与正则表达式匹配类似,还是采用动态规划,x[i][j]表示s的前i个字符和p的前j个字符匹配。如果p[j]!=’*‘,那么s[i]必须与p[j]匹配,即(s[i]==p[j]||p[j]=='?')&&x[i-1][j-1]==true;如果p[j]=='*',那么p[j]可以匹配空字符串,即x[i][j-1]==true即可,或者匹配任意长度的字符串,也就是从x[0][j]到x[i-1][j]存在一个为真,那么x[i][j]为真,实际操作判断更为简单,只需要当x[k-1][j]==true,令x[k][j]=true即可,那么从x[k-1][j]开始到x[x.size()-1][j]都为真。
class Solution {
public:
bool isMatch(string s, string p) {
s=" "+s;
p=" "+p;
int m=s.size();
int n=p.size();
bool x[m][n];
x[0][0]=true;
for(int i=1;i<m;i++)
{
x[i][0]=false;
}
for(int j=1;j<n;j++)
{
if(x[0][j-1]==true&&p[j]=='*')
x[0][j]=true;
else x[0][j]=false;
}
for(int i=1;i<m;i++)
{
for(int j=1;j<n;j++)
{
if(p[j]!='*')
{
if((p[j]==s[i]||p[j]=='?')&&x[i-1][j-1]==true) x[i][j]=true;
else x[i][j]=false;
}
else if(p[j]=='*')
{
if(x[i][j-1]==true) x[i][j]=true;
else if(x[i-1][j]==true) x[i][j]=true;
else x[i][j]=false;
}
}
}
return x[m-1][n-1];
}
};
1148



被折叠的 条评论
为什么被折叠?



