码迷,mamicode.com
首页 > 其他好文 > 详细

Wildcard Matching

时间:2016-04-13 13:10:33      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

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") → 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
int helper(const string& s,const string& p,int i,int j){
    if(j==p.size()&&i==s.size()) return 2;
    if(s.size()==i&&p[j]!=*) return 0;
    if(j==p.size())    return 1;
    if(p[j]==*){
        if(j+1<p.size()&&p[j+1]==*)
            return helper(s,p,i,j+1);
        for(int k=0;k<=s.length()-i;k++){
            int ret=helper(s,p,i+k,j+1);
            if(ret==0||ret==2) return ret;
        }
    }
    if(s[i]==p[j]||p[j]==?){
        return helper(s,p,i+1,j+1);
    }
    return 1;
}

bool isMatch(string s, string p) {
    return helper(s,p,0,0)>1;
}

 

class Solution {

public:
    bool isMatch(string s, string p) 
    {
        int lenS = s.size(), lenP = p.size(), star = lenP, markS = 0, i = 0, j = 0;
        while (i != lenS)
        {
            if (s[i] == p[j] || ? == p[j]) { ++i; ++j; continue; }
            if (* == p[j]) { markS = i; star = j++; continue; }
            if (star != lenP) { i = ++markS; j = star + 1; continue; }
            return false;
        }
        while (* == p[j]) ++j;
        return j == lenP;
    }
};

 

Wildcard Matching

标签:

原文地址:http://www.cnblogs.com/wqkant/p/5386620.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!