繁体   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