面试常遇到的通配符匹配的两个小问题总结

来源:互联网 发布:蒙语输入法软件下载 编辑:程序博客网 时间:2024/06/05 09:06

题目一:给定两个字符串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;    }};


0 0