简体   繁体   English

该算法查找前缀的时间复杂度

[英]The time complexity of this algorithm finding prefix

This algorithm i wrote to check whether one string is a prefix for another string in the array. 我写了这个算法来检查一个字符串是否是数组中另一个字符串的前缀。 The complexity is O(n*(n-1)*k), where n is the number of strings in the array, and K is the largest length of the string. 复杂度为O(n *(n-1)* k),其中n是数组中字符串的数量,K是字符串的最大长度。 Am I right here in complexity analysis? 我在这里进行复杂性分析吗?

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);
}

You're right, I believe. 我相信你是对的。 It's just that K is not exactly that. 仅仅是K不完全是那个。 But roughly speaking it's OK to say so. 但粗略地说,可以这样说。

Also it is K * n * (n-1) / 2 as you don't inspect all 也是K * n * (n-1) / 2因为您不检查所有
ordered couples of strings (you inspect only half of them). 订购几对琴弦(您只检查其中的一半)。
In your example, you inspect 6 couples, not 12. 在您的示例中,您检查6对,而不是12对。

Note that if your strings are say between 1 million and 2 million chars long, 请注意,如果您说的字串长度介于100万到200万个字符之间,
but your n is just say 20 or 50 or 100, then K prevails and this estimate 但您的n只是说20或50或100,则以K为准
is to be interpreted with care. 必须谨慎解释。 Typically one would expect n >> K though, 通常,人们会期望n >> K,
I guess that's what you had in mind too. 我想这也是您的想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM