使用for循环来获得2个字符串之间的汉明距离 [英] Using for loop to get the Hamming distance between 2 strings
问题描述
首先,我制作了2个新的字符串,它们是2个原始字符串,但是两个字母都是降低的,以便比较容易。然后我诉诸使用for循环,如果比较2个字符串。对于这两对字符串中的任何字符差异,循环会将1加到int x = 0。方法的返回值将是这个x的值。
public static int getHammingDistance(String sequence1,String sequence2){
int a = 0;
String sequenceX = sequence1.toLowerCase();
String sequenceY = sequence2.toLowerCase(); (int x = 0; x for(int y = 0; y if(sequenceX.charAt(x)== sequenceY.charAt(y)){
a + = 0;
} else if(sequenceX.charAt(x)!= sequenceY.charAt(y)){
a + = 1;
}
}
}
return a;
}
所以代码看起来不错,任何我可以修复或优化代码?提前致谢。我是一个巨大的noob,所以请原谅我,如果我问什么愚蠢的解决方案
从我的观点下面的实现将是好的: / p>
public static int getHammingDistance(String sequence1,String sequence2){
char [] s1 = sequence1.toCharArray();
char [] s2 = sequence2.toCharArray();
int short = Math.min(s1.length,s2.length);
int longest = Math.max(s1.length,s2.length);
int result = 0;
for(int i = 0; i if(s1 [i]!= s2 [i])result ++;
}
结果+ =最长 - 较短;
返回结果;
$ b 使用数组,避免调用两个方法(charAt)用于每个需要比较的单个字符;
当一个字符串长于另一个字符串时,避免异常
In this task i need to get the Hamming distance (the Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different - from Wikipedia) between the two strings sequence1 and sequence2.
First i made 2 new strings which is the 2 original strings but both with lowered case to make comparing easier. Then i resorted to using the for loop and if to compare the 2 strings. For any differences in characters in these 2 pair of string, the loop would add 1 to an int x = 0. The returns 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 looks good and functional enough? Anything i could to fix or to optimize the code? Thanks in advance. I'm a huge noob so pardon me if i asked anything silly
解决方案 From my point the following implementation would be ok:
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;
}
- uses array, what avoids the invocation of two method (charAt) for each single char that needs to be compared;
- avoid exception when one string is longer than the other.
这篇关于使用for循环来获得2个字符串之间的汉明距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!