zoukankan      html  css  js  c++  java
  • LeetCode "Wildcard Matching"

    Here is the most elegant code I've seen to this problem:

    http://yucoding.blogspot.com/2013/02/leetcode-question-123-wildcard-matching.html

    Simply wow. I added a small tuning: multiple consecutive *s equal a single *:

    class Solution {
    public:
        bool _isMatch(const char *s, size_t lens, const char *p, size_t lenp)
        {
            const char *is = s, *ip = p;
            const char *star = NULL, *starss = NULL; // for *
            while (*is)
            {
                if (*ip == '?' || *ip == *is) { ip++; is++; continue; }
                if (*ip == '*') 
                {
                    if (*(ip + 1) == 0) return true;
                    star = ip ++;
                    starss = is;
                    continue;
                }
                if (star)
                {
                    ip = star + 1;
                    is = ++starss;
                    continue;
                }
                return false;
            }
    
            return *ip == 0 || (*ip == '*' && *(ip + 1) == 0);
        }
        bool isMatch(const char *s, const char *p) {
            size_t lens = strlen(s);
            size_t lenp = strlen(p);
            if (lens == 0 && lenp == 0) return true;
            //    Shrink *s. 
            string sp;
            int id = 0, in = 0;
            char lst = 0;
            while (in < lenp)
            {
                char c = *(p + in);
                if (c == '*' && c == lst)
                {
                    in++;
                    continue;
                }
                else
                {
                    sp += c;
                    id++; in++;
                    lst = c;
                }
            }
            return _isMatch(s, lens, sp.c_str(), sp.length());
        }
    };
  • 相关阅读:
    5.18英语
    5.18
    5.17
    单源点最短路模板
    5.16
    mock.js进行接口mock
    docker-compose安装和使用
    docker常用命令
    docker安装和使用(win10家庭版)
    ES6基础(2)-const
  • 原文地址:https://www.cnblogs.com/tonix/p/3900476.html
Copyright © 2011-2022 走看看