• [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.”
  • 相关阅读:
    pycharm使用技巧
    for 循环
    面向对象进阶
    python实现socket上传下载文件-进度条显示
    python实现进度条--主要用在上传下载文件
    django下常用查询的API
    django下model.py模型的定义
    django下数据库配置
    ORM机制简介
    views.py文件详解
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4584571.html
Copyright © 2020-2023  润新知