Wildcard Matching 包含? * 的字符串匹配问题

来源:互联网 发布:企鹅fm播音软件 编辑:程序博客网 时间:2024/05/16 13:23

一道Leetcode上的题目,挺有意思的

https://oj.leetcode.com/problems/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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "*") → trueisMatch("aa", "a*") → trueisMatch("ab", "?*") → trueisMatch("aab", "c*a*b") → false
就是给定一个源字符串s,一个包含? * 的模式p, ?代表任意单个字符,*代表任意的字符串序列(包括空串),要求判断两者能否匹配

难点在于*符号的处理。

对于* 一种比较好的思路是记录最后一个*出现的位置,然后直接跳过该*, 继续往下匹配,当往下匹配字符发现不匹配时,回到刚才记录的*出现位置的下一位置,同时源字符串跳过当前字符(意思是*匹配当前字符)。

说得不是很清楚,还是从代码中看出其解题思路

 bool isMatch(const char *s, const char *p) {        const char* star=NULL;        const char* ss=s;        while (*s){            //advancing both pointers when (both characters match) or ('?' found in pattern)            //note that *p will not advance beyond its length             if ((*p=='?')||(*p==*s)){s++;p++;continue;}             // * found in pattern, track index of *, only advancing pattern pointer             if (*p=='*'){star=p++; ss=s;continue;}             //current characters didn't match, last pattern pointer was *, current pattern pointer is not *            //only advancing pattern pointer            if (star){ p = star+1; s=++ss;continue;}            //current pattern pointer is not star, last patter pointer was not *           //characters do not match            return false;        }       //check for remaining characters in pattern        while (*p=='*'){p++;}        return !*p;      }



0 0