Match sub-string within a string with tolerance of 1 character mismatch

前端 未结 5 1617
天命终不由人
天命终不由人 2020-12-28 11:07

I was going through some Amazon interview questions on CareerCup.com, and I came across this interesting question which I haven\'t been able to figure out how to do. I have

5条回答
  •  感情败类
    2020-12-28 11:33

    This seems to work, let me know if you find any errors and I'll try to fix them:

    int findHelper(const char *str, const char *substr, int mustMatch = 0)
    {
        if ( *substr == '\0' )
            return 1;
    
        if ( *str == '\0' )
            return 0;
    
        if ( *str == *substr )
            return findHelper(str + 1, substr + 1, mustMatch);
        else
        {
            if ( mustMatch )
                return 0;
    
            if ( *(str + 1) == *substr )
                return findHelper(str + 1, substr, 1);
            else if ( *str == *(substr + 1) )
                return findHelper(str, substr + 1, 1);
            else if ( *(str + 1) == *(substr + 1) )
                return findHelper(str + 1, substr + 1, 1);
            else if ( *(substr + 1) == '\0' )
                return 1;
            else
                return 0;
        }
    }
    
    int find(const char *str, const char *substr)
    {
        int ok = 0;
        while ( *str != '\0' )
            ok |= findHelper(str++, substr, 0);
    
        return ok;
    }
    
    
    int main()
    {
        printf("%d\n", find("xxxdoogyyyy", "dog"));
        printf("%d\n", find("xxxdgyyyy", "dog"));
        printf("%d\n", find("xxxdigyyyy", "dog"));
    }
    

    Basically, I make sure only one character can differ, and run the function that does this for every suffix of the haystack.

提交回复
热议问题