【leetcode 44】 Wildcard Matching 【正确算法】

来源:互联网 发布:淘宝转化率如何计算 编辑:程序博客网 时间:2024/05/02 00:57

/********************************************************************

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)
/************************************************************************

思路:

本题的关键是关于 * 的匹配问题。

1,在 p  中没有出现 * 的时候,对 p  和 s 进行正常的字符匹配。

2,在 p  中出现 * 时,记录 p 中 * 的位置,同时记录此时 s 的位置。

3,从 *  的后面的第一个字符开始匹配。如果匹配失败,返回 s  处,从 s++ 开始重新匹配。


/***********************************************************************

代码:

class Solution{
public:
    bool isMatch(string s, string p){
        return isMatch(s.c_str(), p.c_str());
    }

private:
    bool isMatch(const char *s, const char *p){
        bool star = false;
        const char *str, *ptr;
        for (str = s, ptr = p; *str != '\0'; str++, ptr++){
            switch (*ptr){
            case '?':
                break;
            case '*':
                star = true;
                s = str, p = ptr;
                while (*p == '*') p++;
                if (*p == '\0') return true;
                str = s - 1;
                ptr = p - 1;
                break;
            default:
                if (*str != *ptr){
                    if (!star) return false;
                    s++;
                    str = s - 1;
                    ptr = p - 1;
                }
            }
        }
        while (*ptr == '*') ptr++;
        return (*ptr == '\0');
    }
};


0 0