计算字符串1和字符串2的相似性



我的算法有问题,我尝试了下面提到的示例数据。我不明白为什么结果根本不是我想的那样。例如,当i=3(n(并且j=2(n(时。q的输出应该是2,但它等于1。我想原因可能只是while循环工作出现了问题。但我不知道为什么。请有人帮帮我!非常感谢

运行方法

public static void compareStringToString(String str1, String str2) {
ArrayList<Integer> numSames = new ArrayList<Integer>();
int p = 0, n; // p - Maximum number of similar characters, n - the number of characters of the longer string
// str1 = "slcnsicnn"
// str2 = "ahnscnn"
int i = 0, j = 0;
if (str1.length() >= str2.length()) {
n = str1.length();
for (i = 0; i < n; i++) {
for (j = 0; j < str2.length(); j++) {
if (str1.charAt(i) == str2.charAt(j)) {
p = 0;
while (str1.charAt(i + p) == str2.charAt(j + p)) {
p++;
if ((i + p < n) || (j + p < str2.length())) {
break;
}
}
numSames.add(p);
}
}
}
System.out.println("The similarity of the two strings is: " + (((float)
Collections.max(numSames)) / n) * 100 + "%");
else {
n = str2.length();
// TODO Same things
}

运行屏幕

**

我照你说的做了。我创造了一种新的方法来分割这项工作。事实上,当我这样做的时候,我的头脑变得更清晰了。更具体地说,我能够顺利地运行它,没有错误。或者可能还有一些我还没有注意到的小错误。但这真的很好,就像一点负担。再次感谢你的忠告。

**

// Get the number of similar characters after a pair of similar characters of 2 strings
public static int getNumSimilarAfterChar(String str1, String str2, int indexStr1, int indexStr2) {
int numChar = 0; // It's both a count and an index
// Substrings to work with algorithm
String subStr1;
String subStr2;
if (str1.charAt(indexStr1) == str2.charAt(indexStr2)) {
// Cut substring from highlighted part
subStr1 = str1.substring(indexStr1);
subStr2 = str2.substring(indexStr2);
while (subStr1.charAt(numChar) == subStr2.charAt(numChar)) {
numChar++;
if ((numChar >= (subStr1.length() - 1)) || (numChar >= (subStr2.length() - 1))) {
break;
}
}
return numChar + 1;
} else {
return numChar;
}
}
// Given any two strings of characters, compare the match of these two strings
/**
* Compare the match of string 1 vs string 2
* 
* @param str1
* @param str2
*/
public static void compareStringToString(String str1, String str2) {
ArrayList<Integer> numSames = new ArrayList<Integer>();
// maxSimilar - maximum number of similar characters, totalLength - the number of characters of longer string
int numSimilar = 0, totalLength;
// slcnsicnn
// ahnscnn
int i = 0, j = 0;
// If string 1 is longer than string 2
if (str1.length() >= str2.length()) {
totalLength = str1.length();
for (i = 0; i < totalLength; i++) {
for (j = 0; j < str2.length(); j++) {
// Browse until you come across two similar characters
if (str1.charAt(i) == str2.charAt(j)) {
numSimilar = MyStrings.getNumSimilarAfterChar(str1, str2, i, j);
numSames.add(numSimilar);
System.out.println(numSames.toString());
}
}
}
// Get the max value in a list of how many identical characters are generated           
System.out.println("The similarity of the two strings is: " + (((float) Collections.max(numSames)) / totalLength) * 100 + "%");
} else {
totalLength = str2.length();
// TODO Same things
}
}

相关内容

  • 没有找到相关文章

最新更新