【问题标题】:The time complexity of this algorithm finding prefix该算法查找前缀的时间复杂度
【发布时间】:2014-01-27 16:43:02
【问题描述】:

我写的这个算法是为了检查一个字符串是否是数组中另一个字符串的前缀。 复杂度为 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);
}

【问题讨论】:

  • 可能是个愚蠢的问题(而且完全跑题了),但为什么不使用startsWith呢?
  • 如果您在数组中添加或删除单词并且想要检查前缀很多时间,也许您应该考虑使用另一种数据结构,例如 Trie:en.wikipedia.org/wiki/Trie
  • 是的,尝试更好,但仅用于 BigO 分析
  • startsWith 不错,但是这里只想写算法分析一下。

标签: java algorithm big-o


【解决方案1】:

你是对的,我相信。只是K不完全是 那。不过大体上这么说也行。

也是K * n * (n-1) / 2,因为你没有检查所有
有序的一对字符串(您只检查其中的一半)。
在您的示例中,您检查了 6 对夫妇,而不是 12 对。

请注意,如果您的字符串长度在 100 万到 200 万个字符之间,
但你的 n 只是说 20 或 50 或 100,然后 K 占上风,这个估计
需谨慎解读。通常,人们会期望 n >> K,
我想这也是你的想法。

【讨论】:

  • 为什么说只检查一半?一半是平均水平?最坏的情况应该是K * n^2?
  • 一半还可以。如果您已经对 (strs[0], strs[1]) 进行了检查,则无需检查 (strs[1], strs[0])。
猜你喜欢
  • 2018-09-13
  • 1970-01-01
  • 2014-01-28
  • 2021-08-25
  • 1970-01-01
  • 1970-01-01
  • 2017-04-12
  • 2014-08-29
  • 1970-01-01
相关资源
最近更新 更多