DanMc DanMc - 1 year ago 61
Java Question

Checking if a string matches all characters but one of another string

I have a list of strings and with each string I want to check it's characters against every other string to see if all it's characters are identical except for one.

For instance a check that would return true would be checking

rock against lock

clock and flock have one character that is different, no more no less.

rock against dent will obviously return false.

I have been thinking about first looping through the list and then having a secondary loop within that one to check the first string against the second.

And then using

to create two arrays containing the characters of each string and then checking the array elements against each other (i.e. comparing each string with the same position in the other array 1-1 2-2 etc...) and so long as only one character comparison fails then the check for those two strings is true.

Anyway I have a lot of strings (4029) and considering what I am thinking of implementing at the moment would contain 3 loops each within the other that would result in a cubic loop(?) which would take a long long time with that many elements wouldn't it?

Is there an easier way to do this? Or will this method actually work okay? Or -hopefully not- but is there some sort of potential logical flaw in the solution I have proposed?

Thanks a lot!

Answer Source

Why not do it the naive way?

bool matchesAlmost(String str1, String str2) {
    if (str1.length != str2.length)
        return false;
    int same = 0;
    for (int i = 0; i < str1.length; ++i) {
        if (str1.charAt(i) == str2.charAt(i))
    return same == str1.length - 1;

Now you can just use a quadratic algorithm to check every string against every other.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download