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

前端 未结 5 1620
天命终不由人
天命终不由人 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:40

    This is slightly different than the earlier solution, but I was intrigued by the problem and wanted to give it a shot. Obviously optimize if desired, I just wanted a solution.

    char *match(char *str, char *substr, int tolerance)
    {
      if (! *substr) return str;
      if (! *str) return NULL;
    
      while (*str)
      {
        char *str_p;
        char *substr_p;
        char *matches_missing;
        char *matches_mismatched;
    
        str_p = str;
        substr_p = substr;
    
        while (*str_p && *substr_p && *str_p == *substr_p)
        {
          str_p++;
          substr_p++;
        }
        if (! *substr_p) return str;
        if (! tolerance)
        {
          str++;
          continue;
        }
    
        if (strlen(substr_p) <= tolerance) return str;
    
        /* missed due to a missing letter */
        matches_missing = match(str_p, substr_p + 1, tolerance - 1);
        if (matches_missing == str_p) return str;
    
        /* missed due to a mismatch of letters */
        matches_mismatched = match(str_p + 1, substr_p + 1, tolerance - 1);
        if (matches_mismatched == str_p + 1) return str;
    
        str++;
      }
      return NULL;
    }
    

提交回复
热议问题