LeetCode 44. 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

这道题目和之前有个题目很类似, 本来仿照之前的那个写法,然后T了。

改变一下思路;

对于一个匹配串a和被匹配串b,

a = "bbbbbbbabbaabbabbbbaadd"
b = "b*b*ab**ba*b**b***bba*"

如果他们两个匹配, 则必有在被匹配串b中被*分隔开的字符串, 依次顺序排列在匹配串a中。

即对于b中的子串b, b, ab, ba, b, b, bba。应依次排列在匹配串a中。

如图所示:

  • a = "b b bbbbb ab ba a b b abb bba add"

然后就很容易的写出来一个(n * m)的算法。

但是有一种情况还需考虑

a = "abcabcabc"
b = "abc*abc"

这种情况说明,对于每一个匹配串,不应考虑第一个匹配的,还要考虑后面可以匹配的。

class Solution
{
public:
    bool isMatch(string s, string p)
    {
        int x = 0, y = -1;
        int bs = 0, bp = 0;
        while(bs < s.size())
        {
            if(bp < p.size() && (s[bs] == p[bp] || p[bp] == '?'))
                bs ++, bp ++;
            else if(bp < p.size() && p[bp] == '*')
            {
                if(bp == p.size() - 1)
                    return true;
                x = bs, y = bp ++;
            }
            else if(y != -1)
                bs = ++ x, bp = y+1;
            else
                return false;
        }

        while(bp<p.size() && p[bp] == '*')
            bp ++;

        return bp == p.size();
    }
};
posted @ 2017-03-29 20:14  aiterator  阅读(119)  评论(0编辑  收藏  举报