44. Wildcard Matching

来源:互联网 发布:杭州淘宝美工设计培训 编辑:程序博客网 时间:2024/05/08 06:57

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
class Solution { public:     bool isMatch(string s, string p) {         int slen = s.size(),plen = p.size(),i=0,j=0,iStart=-1,jStart = -1;        while(i < slen){            if(s[i]==p[j]||p[j] == '?'){                i++;                j++;                continue;            }             if(p[j]=='*'){                 iStart = i;                 jStart = j;                 ++j;                 continue;             }             if(iStart >= 0){                 i = iStart+1;                 j = jStart+1;                 iStart++;                 continue;             }             return false;     }         while(p[j] == '*') j++;         return j==plen;     }     };

匹配s和p

如果匹配就s++ , p++

如果不匹配的话就看p之前知否有*,通过iStart来标记,如果出现了最新的*则代替原来的*.因为*abc*,与abcabc的匹配可以知道。

当然是否有*我们需要记录的,遇到*就记录当前*的位置和匹配到的s的位置

然后从*的下一位置匹配,开始匹配0个字符

如果匹配则往后走,如果不匹配则,那么匹配1个字符...同理2,3,4个字符

所以实践复杂度是O(len(s) * len(p))


0 0
原创粉丝点击