zoukankan      html  css  js  c++  java
  • Wildcard Matching

    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

    思路:

    先是递归,不能过大集合;

    循环可以过,但是p == '*'的情况需要特殊处理,用两个指针记录p == '*'时的s和p的位置。

    因为p的*可以代表很多字符,需要确定*代表s中的那些字符

    代码:

    递归版

    class Solution {
    public:
        bool isMatch(const char *s, const char *p) {
            if (*p == '*')
            {
                while (*p == '*')   p++;
                if (*p == '') return true;
                while (*s != '' && !isMatch(s, p))
                    s++;
                return *s != '';
            }
            else if (*p == '' || *s == '')
                return *p == *s;
            else if (*p == '?' || *p == *s)
                return isMatch(++s, ++p);
            else return false;
        }
    };
    

     循环版

    class Solution {
    public:
        bool isMatch(const char *s, const char *p)
        {
            if (!s && !p)
                return true;
    
            const char *ss = NULL;
            const char *sp = NULL;
    
            while (*s)
            {
                if (*s == *p || *p == '?')
                {
                    s++;
                    p++;
                }
                else if (*p == '*')
                {
                    while (*p == '*')
                        p++;
                    if (*p == '')
                        return true;
                    ss = s;
                    sp = p;
                }
                else if ((*p == '' || *p != *s) && sp)
                {
                    s = ++ss;
                    p = sp;
                }
                else return false;
            }
            while (*p)
                if (*p++ != '*')
                    return false;
            return true;
        }
    };
  • 相关阅读:
    [2018福大至诚软工助教]原型设计+用户规格说明书小结
    高等数理逻辑大作业
    [2018福大至诚软工助教]测试与优化小结
    [2018福大至诚软工助教]结对项目小结
    BETA 版冲刺前准备
    Alpha冲刺之事后诸葛亮
    Alpha 冲刺 (10/10)
    Alpha 冲刺 (9/10)
    Alpha 冲刺 (8/10)
    Alpha 冲刺 (7/10)
  • 原文地址:https://www.cnblogs.com/dollarzhaole/p/3250983.html
Copyright © 2011-2022 走看看