Java – use the for loop to get the Hamming distance between two strings

In this task, I need to obtain the Hamming distance between two strings sequence1 and sequence2 (the Hamming distance between two strings of equal length is the number of positions where the corresponding symbol is different from Wikipedia)

First of all, I made two new strings. These are two original strings, but both use lower watchcases to make it easier Then I use the for loop if I want to compare two strings For any difference between the characters in the two pairs of strings, the loop adds 1 to int x = 0 The return value of the method will be the value of this X

public static int getHammingDistance(String sequence1,String sequence2) {
    int a = 0;
    String sequenceX = sequence1.toLowerCase();
    String sequenceY = sequence2.toLowerCase();
    for (int x = 0; x < sequenceX.length(); x++) {
        for (int y = 0; y < sequenceY.length(); y++) {
            if (sequenceX.charAt(x) == sequenceY.charAt(y)) {
                a += 0;
            } else if (sequenceX.charAt(x) != sequenceY.charAt(y)) {
                a += 1;
            }
        }
    }
    return a;
}

So does the code look good and functional? Can I fix or optimize anything in the code? Thank you in advance I am a huge rookie. If I ask any stupid questions, please forgive me

Solution

From my point of view, the following implementations are possible:

public static int getHammingDistance(String sequence1,String sequence2) {
    char[] s1 = sequence1.tocharArray();
    char[] s2 = sequence2.tocharArray();

    int shorter = Math.min(s1.length,s2.length);
    int longest = Math.max(s1.length,s2.length);

    int result = 0;
    for (int i=0; i<shorter; i++) {
        if (s1[i] != s2[i]) result++;
    }

    result += longest - shorter;

    return result;
}

>Use arrays to avoid calling two methods (charat) for each single char that needs to be compared; > Avoid exceptions when one string is longer than another

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>