您的位置:首页 > 其它

Leetcode -- Wildcard Matching

2015-10-29 16:23 363 查看
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

分析:

递归算法会超时,因此采用了while循环的写法:

class Solution {
public:
bool isMatch(string s, string p) {
size_t i=0,j=0,star=-1,beg;
if(p.empty()) return s.empty();
while(i<s.size())
{
if(s[i]==p[j]||p[j]=='?')
{
i++;j++;
continue;
}
if(p[j]=='*')
{
star=j++;
beg=i;
continue;
}
if(star>=0)
{
j=star+1;
i=++beg;
continue;
}
return 0;
}
while(p[j]=='*') j++;
return j==p.size();
}
};


整体思路还是在出现\(\star\)的时候对s字符串往后的每个位置进行匹配。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: