面試常遇到的萬用字元匹配的兩個小問題總結

life4711發表於2016-05-05

題目一:給定兩個字串s和p,s為原串,p為含有萬用字元的串,其中關於萬用字元的定義為:“*”表示可以匹配任意字串,“.”表示可以匹配任意字元

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

        while (*s && *p)
        {
            if (*s != *p)
            {
                if (*p == '?') s++, p++;
                else if (*p == '*')
                {
                    while(*p == '*') p++;//跳過連續的*號
                    if (*p == '\0') return true;//如果跳過*號就到達結尾,那麼是匹配的
                    while (*s)
                    {
                        if (isMatch(s, p)) return true;//不停的嘗試
                        s++;
                    }
                }
                else return false;
            }
            else s++, p++;
        }
        return isMatch(s, p);
    }
};

題目二:給定兩個字串s和p,s為原串,p為含有萬用字元的串,其中關於萬用字元的定義為:“*”表示前面的字元可以出現任意多次(包括 0),“.”表示可以匹配任意字元

class Solution
{
public:
    bool isMatch(const char *s, const char *p)
    {
        if (s == NULL || p == NULL)
            return false;
        if (*p == '\0')
            return  *s == '\0';

        if (*(p+1) == '*')
        {
            //
            // notice: ".*" means repeat '.' 0 or more times
            //
            while ((*s != '\0' && *p == '.') || *s == *p)
            {
                if (isMatch(s, p + 2))
                    return true;
                s += 1;
            }
            return isMatch(s, p + 2);
        }
        else if ((*s != '\0' && *p == '.') || *s == *p)
        {
            return isMatch(s + 1, p + 1);
        }
        return false;
    }
};


相關文章