我从互联网上看到了很多资源,但是找不到确切的帮助。我试图找出两个字符串示例之间的编辑距离: 字符串a =“在段gioo之间放入返回”; 字符串b =“在电话gio之间打招呼”; 在这里,我总是将String a与其他字符串进行比较,因此此处的编辑距离应为4。 我已经完成了一些代码执行,将其与字符串中的每个字符进行比较。
int len1 = row10.length();
int len2 = row01.length();
int[][] dp = new int[len1 + 1][len2 + 1];
for (int i = 0; i <= len1; i++) {
dp[i][0] = i;
}
for (int j = 0; j <= len2; j++) {
dp[0][j] = j;
}
for (int i = 0; i < len1; i++) {
char c1 = row10.charAt(i);
for (int j = 0; j < len2; j++) {
char c2 = row01.charAt(j);
if (c1 == c2) {
dp[i + 1][j + 1] = dp[i][j];
} else {
int replace = dp[i][j] + 1;
int insert = dp[i][j + 1] + 1;
int delete = dp[i + 1][j] + 1;
int min = replace > insert ? insert : replace;
min = delete > min ? min : delete;
dp[i + 1][j + 1] = min;
}
}
}
System.out.println(dp[len1][len2]);
答案 0 :(得分:1)
制作了示例函数。它实际上并没有考虑到极端情况,但它可以工作。另外,请考虑单词的大小写敏感性。
package test;
public class CalcWordDiff {
public static void main(String[] args) {
// TODO Auto-generated method stub
String a = "My name is ABC.";
String b = "My name xyz.";
System.out.println("Edit distance will be : "+calcDistanceBetweenWords(a,b));
}
public static int calcDistanceBetweenWords(String first, String second)
{
int res = 0;
String[] words_string_first = first.trim().split(" "); // By trim, I removed the Whitespaces if they exist
String[] words_string_second = second.trim().split(" ");
//Check the length of both the arrays
System.out.println("Size of arrays first is : "+words_string_first.length);
System.out.println("Size of arrays second is : "+words_string_second.length);
int lowerWordSentSize = 0;
if(words_string_first.length<=words_string_second.length)
{
lowerWordSentSize = words_string_first.length;
}
else
{
lowerWordSentSize = words_string_second.length;
}
//Now iterate through the array of lower size
for(int i = 0; i< lowerWordSentSize; i++)
{
if(words_string_first[i].equals(words_string_second[i]))
{
//Do nothing, it means both the words are same
}
else
{
System.out.println("Words mismatched at "+(i+1)+" th Position.");
res = i;
}
}
return res;
}
}