• LeetCode 44. 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
    

    这道题目和之前有个题目很类似, 本来仿照之前的那个写法,然后T了。

    改变一下思路;

    对于一个匹配串a和被匹配串b,

    a = "bbbbbbbabbaabbabbbbaadd"
    b = "b*b*ab**ba*b**b***bba*"
    

    如果他们两个匹配, 则必有在被匹配串b中被*分隔开的字符串, 依次顺序排列在匹配串a中。

    即对于b中的子串b, b, ab, ba, b, b, bba。应依次排列在匹配串a中。

    如图所示:

    • a = "b b bbbbb ab ba a b b abb bba add"

    然后就很容易的写出来一个(n * m)的算法。

    但是有一种情况还需考虑

    a = "abcabcabc"
    b = "abc*abc"
    

    这种情况说明,对于每一个匹配串,不应考虑第一个匹配的,还要考虑后面可以匹配的。

    class Solution
    {
    public:
        bool isMatch(string s, string p)
        {
            int x = 0, y = -1;
            int bs = 0, bp = 0;
            while(bs < s.size())
            {
                if(bp < p.size() && (s[bs] == p[bp] || p[bp] == '?'))
                    bs ++, bp ++;
                else if(bp < p.size() && p[bp] == '*')
                {
                    if(bp == p.size() - 1)
                        return true;
                    x = bs, y = bp ++;
                }
                else if(y != -1)
                    bs = ++ x, bp = y+1;
                else
                    return false;
            }
    
            while(bp<p.size() && p[bp] == '*')
                bp ++;
    
            return bp == p.size();
        }
    };
    
  • 相关阅读:
    SparkSQL UDF使用方法与原理详解
    Hadoop 之日志管理—应用在 YARN 中运行时的日志
    圣诞节雪花效果,pc端
    转 redis使用场景 简介
    转 springboot 教程
    springboot freeMarker
    springboot web 服务器选择
    springboot 异步任务
    springboot 整合 rabbitmq
    软件开发生命周期过程中,必须考虑的安全问题
  • 原文地址:https://www.cnblogs.com/aiterator/p/6641546.html
Copyright © 2020-2023  润新知