44. Wildcard Matching
problem description
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:
s
could be empty and contains only lowercase lettersa-z
.p
could 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
algorithm thought
这题很之前的正则表达式很像,其实还简单一点。使用二维数组保存中间结果,动态规划解决问题。可以借鉴前面动态规划题目的解答。这里的?其实和之前的.一样。这里的*比之前的*更加加单
code
class Solution {
public:
bool isMatch(string s, string p) {
vector<bool>(p.size()+1,false);
for(int i=1;i<=p.size();++i)
if(p[i-1]=='*'){
res[0][i]=true;
}
else
break;
res[0][0]=true;
for(int i=1;i<=s.size();++i){
for(int j=1;j<=p.size();++j){
if(p[j-1]=='?'||s[i-1]==p[j-1]){
res[i][j]=res[i-1][j-1];
}
else if(p[j-1]=='*'){
if(res[i-1][j]||res[i][j-1])
res[i][j]=true;
}
}
}
return res[s.size()][p.size()];
}
};
algorithm analysis
时间复杂度O(n²)
Last updated