您的位置:首页 > 其它

LeetCode44. Wildcard Matching

2016-11-16 00:10 399 查看
题意: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

贪心+回溯

空间复杂度O(1)

时间复杂度约为O(n), 最坏情况O(n*n)

pos1记录扫描到的字符串s的位置,

pos2记录扫描到的字符串p的位置,

match_pos记录*匹配到的位置,

star记录*的下标,

当pos1还没有到达字符串尾,

如果pos2表示?或者pos2对应的字符等于pos1对应的字符,则表示该字符匹配,pos1,pos2都向后一步.

否则,如果pos2表示*, match_pos=pos1,star=pos2,pos2向后一步。此时*如果要匹配,首先要匹配pos1位置的字符。

否则,如果之前遇到过*,那么就利用该* 匹配一个字符,即match_pos加1. 同时更新此时的pos1,pos2。pos1=match_pos, pos2等于*的下一个字符的位置。

bool isMatch(string s, string p) {
int pos1 = 0, pos2 = 0;
int match_pos = 0;
int star = -1;

while(pos1 < s.size()){
if(pos2 < p.size() && p[pos2] == '?' || p[pos2] == s[pos1]){
pos1++;
pos2++;
}
else if(pos2 < p.size() && p[pos2] == '*'){
star = pos2;
match_pos = pos1;
pos2++;
}
else if(star != -1){
match_pos++;
pos1 = match_pos;
pos2 = star + 1;
}
else return false;
}

for(int i = pos2; i < p.size(); ++i)
if(p[i] != '*') return false;

return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode