• [LeetCode] #44 Wildcard Matching


    mplement 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

    本题是匹配问题,如果遇到‘?’就匹配任意一个字符,如果是‘*’,匹配0-n个字符。利用贪心算法求解。时间:20ms。代码如下:
    class Solution {
    public:
        bool isMatch(string s, string p) {
            if (p.empty()) 
                return s.empty();
            string::const_iterator pter = p.begin(), ster = s.begin();
            string::const_iterator star_p, star_s;
            bool sign = false;
            while (ster!=s.end()){
                if (pter == p.end()){
                    if (sign){
                        ster = ++star_s;
                        pter = star_p;
                    }
                    else
                        break;
                }
                else if (*pter == '?' || *pter == *ster)
                    ++pter, ++ster;
                else if (*pter == '*'){
                    while (pter != p.end() && (*pter == '*' || *pter == '?')){
                        if (*pter == '?'){
                            ++pter;
                            ++ster;
                            if (ster == s.end())
                                break;
                        }
                        else
                            ++pter;
                    }
                    if (pter==p.end()) 
                        return true;
                    star_p = pter;
                    star_s = ster;
                    sign = true;
                }
                else if ((*pter != *ster || *pter!='?') && sign){
                    ster = ++star_s;
                    pter = star_p; 
                }
                else
                    return false;
            }
            if (ster != s.end())
                return false;
            while (pter!=p.end())
                if (*pter++ != '*')
                    return false;
            return true;
        }
    };
    “If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.”
  • 相关阅读:
    matplotlib直方图绘图并且标注数字
    爬虫最基础知识串行和异步进阶代码
    卡方检验
    德国VoIP 系统中发现秘密后门
    python 处理字典键值合并
    python 读取json大文件
    上下文管理器的使用
    服务端高并发分布式架构
    上下文管理器连接数据库示例
    上下文管理器
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4584571.html
Copyright © 2020-2023  润新知