簡體   English   中英

該算法查找前綴的時間復雜度

[英]The time complexity of this algorithm finding prefix

我寫了這個算法來檢查一個字符串是否是數組中另一個字符串的前綴。 復雜度為O(n *(n-1)* k),其中n是數組中字符串的數量,K是字符串的最大長度。 我在這里進行復雜性分析嗎?

public static void isPrefix(String[] strs){

    for(int i=0; i<strs.length; i++){
        for(int j=i+1; j<strs.length; j++){
            String a = strs[i];
            String b = strs[j];

            if(!commonStr(a,b).isEmpty()){
                System.out.println(a + "->" + b);
            }
        }
    }
}

private static String commonStr(String a, String b){
    int smaller = Math.min(a.length(), b.length());
    for(int k=0; k<smaller; k++){
        if(a.charAt(k) != b.charAt(k)){
            return "";
        }
    }
    return a.substring(0,smaller);
}

public static void main(String[] args){
    String[] strs = {"ab", "abc", "cde", "abef"};
    isPrefix(strs);
}

我相信你是對的。 僅僅是K不完全是那個。 但粗略地說,可以這樣說。

也是K * n * (n-1) / 2因為您不檢查所有
訂購幾對琴弦(您只檢查其中的一半)。
在您的示例中,您檢查6對,而不是12對。

請注意,如果您說的字串長度介於100萬到200萬個字符之間,
但您的n只是說20或50或100,則以K為准
必須謹慎解釋。 通常,人們會期望n >> K,
我想這也是您的想法。

暫無
暫無

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

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