Java - 排名/匹配句子

标签 java

我正在寻找一种对两个句子进行排名/匹配的方法。

例如,取以下2个例句。

  1. 这是一个简短的句子。
  2. 这是一个包含很多单词的长句子。

我的新句子是这是一个句子。

我想将我的新句子与现有句子进行比较。我的新句子几乎与句子 1 匹配,但仅部分与句子 2 匹配。

我可以有一个算法或工作示例,以便我可以对我的新句子进行排名。与新句子相比,句子 1 应该具有较高的排名,句子 2 的排名较低。我的编码语言是 Java。

最佳答案

public class Main {
    public static int getLevenshteinDistance(String s, String t) {
        if (s == null || t == null) {
            throw new IllegalArgumentException("Strings must not be null");
        }
        int n = s.length(); // length of s
        int m = t.length(); // length of t

        if (n == 0) {
            return m;
        } else if (m == 0) {
            return n;
        }

        if (n > m) {
            // swap the input strings to consume less memory
            String tmp = s;
            s = t;
            t = tmp;
            n = m;
            m = t.length();
        }

        int p[] = new int[n + 1]; // 'previous' cost array, horizontally
        int d[] = new int[n + 1]; // cost array, horizontally
        int _d[]; // placeholder to assist in swapping p and d

        // indexes into strings s and t
        int i; // iterates through s
        int j; // iterates through t

        char t_j; // jth character of t

        int cost; // cost

        for (i = 0; i <= n; i++) {
            p[i] = i;
        }

        for (j = 1; j <= m; j++) {
            t_j = t.charAt(j - 1);
            d[0] = j;

            for (i = 1; i <= n; i++) {
                cost = s.charAt(i - 1) == t_j ? 0 : 1;
                // minimum of cell to the left+1, to the top+1, diagonally left
                // and up +cost
                d[i] = Math.min(Math.min(d[i - 1] + 1, p[i] + 1), p[i - 1] + cost);
            }

            // copy current distance counts to 'previous row' distance counts
            _d = p;
            p = d;
            d = _d;
        }

        // our last action in the above loop was to switch d and p, so p now
        // actually has the most recent cost counts
        return p[n];
    }

}

关于Java - 排名/匹配句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27921507/

相关文章:

java - 有没有有效的方法使用 GSON 将 org.json.JSONObject 转换为 POJO 模型?

javascript - AJAX调用SpringBoot Controller 导致CORS错误

java - Spring Boot 和 buildResponseEntity()

java - Spring MVC 4 + Tomcat 7,如何用JavaConfig实现HTTPS?

Java - 如何使用 JavaScriptExecutor 调用字符串内的变量?

java - Spring Boot 具有更多上下文

java - 我们可以使用java更新受密码保护的Excel工作表的行和列吗?

java - [ ][ ] 和 if 语句在代码中不起作用

java - MySQL 数据未显示在 Android RecyclerView 中(Logcat 错误 : Couldn't load memtrack module)

java - java 的 native 内存跟踪输出的 "other"部分有什么内容?