赵乐ACM

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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 == '*'的情况需要特殊处理,用两个指针记录p == '*'时的s和p的位置。

因为p的*可以代表很多字符,需要确定*代表s中的那些字符

 

代码:

递归版

class Solution {
public:
    bool isMatch(const char *s, const char *p) {
        if (*p == '*')
        {
            while (*p == '*')   p++;
            if (*p == '\0') return true;
            while (*s != '\0' && !isMatch(s, p))
                s++;
            return *s != '\0';
        }
        else if (*p == '\0' || *s == '\0')
            return *p == *s;
        else if (*p == '?' || *p == *s)
            return isMatch(++s, ++p);
        else return false;
    }
};


 循环版

class Solution {
public:
    bool isMatch(const char *s, const char *p)
    {
        if (!s && !p)
            return true;

        const char *ss = NULL;
        const char *sp = NULL;

        while (*s)
        {
            if (*s == *p || *p == '?')
            {
                s++;
                p++;
            }
            else if (*p == '*')
            {
                while (*p == '*')
                    p++;
                if (*p == '\0')
                    return true;
                ss = s;
                sp = p;
            }
            else if ((*p == '\0' || *p != *s) && sp)
            {
                s = ++ss;
                p = sp;
            }
            else return false;
        }
        while (*p)
            if (*p++ != '*')
                return false;
        return true;
    }
};
posted on 2013-08-11 09:05  赵乐ACM  阅读(350)  评论(0编辑  收藏  举报