問題描述
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
問題分析
- ******* ,連續的*,預處理的時候可以合併爲一個*
- abc?d?,字母或?組合,後面都簡寫爲X
- 通配符字符串只有******或者X
- X*X*X或*X*X或者X*X*或者*X*這幾種類型中的一種
代碼
//Runtime: 41 ms
class Solution {
public:
bool fun(string s, string p){
if (s.length() != p.length()) return false;
for (int i = 0; i < s.length(); i++){
if (s[i] == p[i] || p[i] == '?')
continue;
else return false;
}
return true;
}
bool isMatch(string s, string p) {
int slen = s.length();
int plen = p.length();
vector<string> arr;
if (!plen&&!slen) return true;
if (!plen) return false;
int single_count = 0;
//預處理,將*******X****X****此類的串轉爲*X*X*的形式
for (int i = 0; i < plen; ){
if (p[i] == '*'){
string v = "*";
arr.push_back(v);
i++;
while (i < plen&&p[i] == '*') i++;
}
else{
string v;
v += p[i];
i++;
single_count++;
while (i < plen&&p[i] != '*') {
v+=p[i]; i++;
single_count++;
}
arr.push_back(v);
}
}
if (slen < single_count) return false;
//這裏的x,y均值的是包含字母或?的字符串
//情況一:y或*
if (arr.size() == 1){
if (arr[0] == "*") return true;
else return fun(s, arr[0]);
}
//情況二:y*x*x*y or y*x* or *x*y三種情況的y
int left=0;
int right = slen ;
if (arr[0] != "*"){
int size = arr[0].size();
if (size > slen) return false;
if(fun(s.substr(0, arr[0].size()), arr[0]) == false) return false;
left = size;
}
if (arr.back() != "*"){
int size = arr.back().size();
if (size > slen) return false;
if(fun(s.substr(slen - arr.back().length()), arr.back()) == false) return false;
right = slen - size;
arr.pop_back();
}
int x = 1;
while (x < arr.size()){
if (arr[x] != "*"){
int flag = 0; //標記是否在s以left開頭的子串中是否有匹配項
while (left<right){
if (right - left < arr[x].length()) return false; //判斷是否s有足夠長度的串去匹配,沒有則直接返回false
if (fun(s.substr(left, arr[x].length()), arr[x])){
left += arr[x].length();
flag = 1;
break;
}
else{
left++;
}
}
if (!flag) return false; //如果沒有找到任何匹配位置,則直接返回false
}
x++;
}
if (x == arr.size()) return true; //全部匹配則true
return false;
}
};