凌云的博客

成功=工作+游戏+少说空话

LeetCode 算法题 44. Wildcard Matching

分类:algorithm| 发布时间:2016-10-10 10:47:00


题目

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

题意

实现支持 '?' 以及 '*' 的通配符匹配。

解法

class Solution {
public:
    bool isMatch(string in_s, string in_p) {
        const char *s = in_s.c_str(), *p = in_p.c_str();
        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');
    }
};