【发布时间】:2017-05-17 04:03:32
【问题描述】:
我有两个多行字符串。我正在使用以下代码来确定其中两个之间的相似性。这利用了 Levenshtein 距离算法。
public static double similarity(String s1, String s2) {
String longer = s1, shorter = s2;
if (s1.length() < s2.length()) {
longer = s2; shorter = s1;
}
int longerLength = longer.length();
if (longerLength == 0) { return 1.0; /* both strings are zero length */ }
return (longerLength - editDistance(longer, shorter)) / (double) longerLength;
}
public static int editDistance(String s1, String s2) {
s1 = s1.toLowerCase();
s2 = s2.toLowerCase();
int[] costs = new int[s2.length() + 1];
for (int i = 0; i <= s1.length(); i++) {
int lastValue = i;
for (int j = 0; j <= s2.length(); j++) {
if (i == 0)
costs[j] = j;
else {
if (j > 0) {
int newValue = costs[j - 1];
if (s1.charAt(i - 1) != s2.charAt(j - 1))
newValue = Math.min(Math.min(newValue, lastValue),
costs[j]) + 1;
costs[j - 1] = lastValue;
lastValue = newValue;
}
}
}
if (i > 0)
costs[s2.length()] = lastValue;
}
return costs[s2.length()];
}
但是上面的代码没有按预期工作。
例如,假设我们有以下两个字符串,例如 s1 和 s2,
S1 -> How do we optimize the performance? . What should we do to compare both strings to find the percentage of similarity between both?
S2->How do we optimize tje performance? What should we do to compare both strings to find the percentage of similarity between both?
然后我将上述字符串传递给相似性方法,但它没有找到确切的差异百分比。如何优化算法?
以下是我的主要方法
更新:
public static boolean authQuestion(String question) throws SQLException{
boolean isQuestionAvailable = false;
Connection dbCon = null;
try {
dbCon = MyResource.getConnection();
String query = "SELECT * FROM WORDBANK where WORD ~* ?;";
PreparedStatement checkStmt = dbCon.prepareStatement(query);
checkStmt.setString(1, question);
ResultSet rs = checkStmt.executeQuery();
while (rs.next()) {
double re=similarity( rs.getString("question"), question);
if(re > 0.6){
isQuestionAvailable = true;
}else {
isQuestionAvailable = false;
}
}
} catch (URISyntaxException e1) {
e1.printStackTrace();
} catch (SQLException sqle) {
sqle.printStackTrace();
} catch (Exception e) {
if (dbCon != null)
dbCon.close();
} finally {
if (dbCon != null)
dbCon.close();
}
return isQuestionAvailable;
}
【问题讨论】:
-
看看Apache's implementation有没有什么想法。
-
那么,你得到了多少百分比,你期望得到什么,为什么?另外,“优化算法”是什么意思?优化性能,还是您的意思是“修复”它,直到它达到您的预期?
-
修复它unitl我得到了我想要的。它始终打印 100%
-
我需要注意您的代码不会打印任何内容。我刚刚尝试了您在代码中出现的两个字符串,它给出了
96.94656488549618%,所以不是 100%。从中我得出结论,问题可能出在您用于打印输出的代码中,或者您可能没有正确运行它。请包括您的main方法。 -
我不确定您打算如何处理 SQL 查询。如果您使用 S1 字符串进行搜索,您将不会在数据库中找到您的 S2。您在查询中使用的
~*运算符是 postgresql 不区分大小写的正则表达式匹配运算符,但您传入的字符串不是正则表达式。因此,如果它在数据库中找不到匹配项,则永远不会进入您的while循环,并且isQuestionAvailable仍然是false。
标签: java algorithm levenshtein-distance