Wildcard Matching

来源:互联网 发布:python 时间戳加减 编辑:程序博客网 时间:2024/06/09 14:17

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
解题思路:这题真是让我蛋疼啊。看错题了,用DP去解,TLE,因为字符串长度很长。后来才发现s仅仅是一个普通的字符串,p为一个含有通配符的字符串。这样的话我们便可以线性处理,我们主要保存当前位置之前的最后一个*的位置即可而不需要考虑前面的*号,如果s和p匹配,则s后面肯定是存在一部分子串和p的后面部分的子串是匹配的,否则不匹配,这样只处理当前位置前的最后一个*的位置,便能使我们的串达到匹配的目的。
class Solution {public:    bool isMatch(string s, string p) {        int n = s.length();        int m = p.length();        int id1 = 0, id2 = 0;        int ps = -1, ss;        bool ok = true;        while(id1 < n) {            if(s[id1] == p[id2] || p[id2] == '?') {                id1++;                id2++;                continue;            }            if(p[id2] == '*') {                ps = id2;                ss = id1;                id2++;                continue;            }            if(ps != -1) {                id2 = ps + 1;                id1 = ss + 1;                ++ss;                continue;            }            ok = false;            break;        }        while(p[id2] == '*') id2++;        return ok && id2 >= m;    }};


0 0