您的位置:首页 > 其它

[leetcode] 44. Wildcard Matching 解题报告

2016-04-02 15:22 417 查看
题目链接: https://leetcode.com/problems/wildcard-matching/
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


思路: 有两种特殊字符, '?'代表匹配一个任意字符, 这个比较好处理. '*'匹配任意多个字符, 这个需要考虑匹配多个字符. 因此我们可以记下最后出现'*'的位置, 这样当后面位置不匹配的时候再回到这里将不匹配的字符用'*'来匹配. 这样最后再判断是否p指针停留的位置到最后都是*, 如果是的话则可以匹配, 否则不可以匹配. 一个例子如: s = "aa", p = "aa****".

代码如下:

class Solution {
public:
bool isMatch(string s, string p) {
int old_s, old_p = -1, pos_s = 0, pos_p = 0;
while(pos_s < s.size())
{
if(s[pos_s]==p[pos_p] || p[pos_p]=='?')
pos_s++, pos_p++;
else if(p[pos_p] == '*')
old_s = pos_s+1, old_p = pos_p, pos_p++;
else if(old_p != -1)
pos_s = old_s, pos_p = old_p;
else return false;
}
while(pos_p < p.size() && p[pos_p] == '*') pos_p++;
return pos_p == p.size();
}
};
参考: https://leetcode.com/discuss/49254/fastest-non-dp-solution-with-o-1-space
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: