sundeepblue
4/27/2014 - 12:00 PM

count the match of a pattern

count the match of a pattern

bool is_match(string &s, const string &p) {
    if(s.empty() || p.empty()) return false;
    int ns = s.size(), np = p.size();
    if(ns < np) return false;
    int i = 0;
    while(i < np) {
        if(s[i] != p[i]) return false;
        i++;
    }
    return true;
}
int count_match(string &s, const string &p) {
    if(s.empty()) return 0;
    if(p.empty()) return 0;
    int ns = s.size(), np = p.size();
    if(ns < np) return 0;
    
    int i = 0;
    int count = 0;
    while(i < ns) {
        string sub = s.substr(i);
        if(is_match(sub, p)) {
            count++;
        }
        i++;
    }
    return count;
}