Search code examples
javastringmismatch

Java match string with x allowed mismatches.


What is the fastest / clearest way to see if a string matches to another string of the same length with X allowed mismatches? Is there a library that can do this, its not in Apache stringUtils (there is only one that also uses insertions / deletions).

So lets say I have 2 string of length for and I want to know if they match with 1 mismatch allowed. Insertions and deletions are not allowed.

So:

ABCD <-> ABCD = Match

ABCC <-> ABCD = Match with 1 mismatch

ACCC <-> ABCD = no match, 2 mismatches is too much.


Solution

  • String str1, str2;
    

    Assuming the lengths of the strings are equal:

    int i = 0;
    
    for(char c : str1.toCharArray())
    {
       if(c != str2.charAt(i++))
          counter++;
    }
    
    if(counter > 1)
      // mismatch