簡體   English   中英

查找兩個字符串之間最短路徑的數據結構

[英]Datastrutcture for finding shortest path between two strings

我正在創建一個程序,該程序將使用5000個字符串的單詞列表,並找到從一個字符串到另一個字符串的最短路徑。 例如,abc-> bac可以顯示“ abc,bbc,bac”。

我很確定自己想做什么,唯一不確定的是什么數據結構應該代表我的單詞表。 目標是搜索(BFS)盡可能快地運行,因此犧牲一些空間是沒有問題的。 我在考慮BST或鄰接表,但是由於我不是datastrutcutres的時間復雜性方面的專家,因此我想在開始調整代碼之前先確定一下。 誰能推薦其中一個結構而不是另一個? 還是我可能錯過了一個顯然可以替代這種情況的數據結構?

看起來您正在尋找的是Levenshtein距離這是Rosetta代碼實現 ,您應該能夠更改它以滿足您的需要:

public class Levenshtein {

    public static int distance(String a, String b) {
        a = a.toLowerCase();
        b = b.toLowerCase();
        // i == 0
        int [] costs = new int [b.length() + 1];
        for (int j = 0; j < costs.length; j++)
            costs[j] = j;
        for (int i = 1; i <= a.length(); i++) {
            // j == 0; nw = lev(i - 1, j)
            costs[0] = i;
            int nw = i - 1;
            for (int j = 1; j <= b.length(); j++) {
                int cj = Math.min(1 + Math.min(costs[j], costs[j - 1]), a.charAt(i - 1) == b.charAt(j - 1) ? nw : nw + 1);
                nw = costs[j];
                costs[j] = cj;
            }
        }
        return costs[b.length()];
    }

    public static void main(String [] args) {
        String [] data = { "kitten", "sitting", "saturday", "sunday", "rosettacode", "raisethysword" };
        for (int i = 0; i < data.length; i += 2)
            System.out.println("distance(" + data[i] + ", " + data[i+1] + ") = " + distance(data[i], data[i+1]));
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM