sundeepblue
4/23/2014 - 7:53 PM

Write a function to check if a given string matches a given pattern as a non-contiguous substring: that is, all the characters in the patter

Write a function to check if a given string matches a given pattern as a non-contiguous substring: that is, all the characters in the pattern appear in the text string in the same order, but possibly not all in a row (eg: pwdp matches passwordparser.h and pwdafterpepper.cc)

bool is_match(char *str, char *pattern) {
    int i=0, j=0;
    while(str[i] != '\0' && pattern[j] != '\0') {
        if(str[i] == pattern[j]) j++;
        i++;
    }
    if(pattern[j] == '\0') return true;
    return false;
}

// or more concisely
bool is_match(char *str, char *pattern) {
    int i=0, j=0;
    while(str[i] && pattern[j]) {
        if(str[i] == pattern[j]) j++;
        i++;
    }
    return pattern[j] == 0;
}