【问题标题】:Time complexity of a string compression algorithm字符串压缩算法的时间复杂度
【发布时间】:2016-04-30 17:46:41
【问题描述】:

我尝试从破解关于压缩字符串的代码面试书做一个练习:

实现一种使用计数的方法来执行基本的字符串压缩 重复的字符。例如,字符串 aabcccccaaa 将变为 a2blc5a3。如果“压缩”字符串不会变得小于原始字符串 字符串,你的方法应该返回原始字符串。

作者给出的第一个命题如下:

public static String compressBad(String str) {
    int size = countCompression(str);
    if (size >= str.length()) {
        return str;
    }
    String mystr = "";
    char last = str.charAt(0);
    int count = 1;
    for (int i = 1; i < str.length(); i++) {
        if (str.charAt(i) == last) {
            count++;
        } else {
            mystr += last + "" + count;
            last = str.charAt(i);
            count = 1;
        }
    }
    return mystr + last + count;
}

关于这个算法的时间复杂度,她说:

运行时间为 0(p + k^2),其中 p 是原始字符串的大小,k 是字符序列的数量。例如,如果字符串是 aabccdeeaa,则有六个字符序列。这很慢,因为字符串连接在 0(n^2) 时间内运行

我有两个主要问题:

1) 为什么时间复杂度是O(p+k^2),应该只有O(p)(其中p是字符串的大小)不是吗?因为我们只做 p 次迭代而不是 p + k^2。

2) 为什么字符串拼接的时间复杂度是0(n^2)??? 我认为如果我们有一个 string3 = string1 + string2 那么我们有一个 size(string1) + size(string2) 的复杂度,因为我们必须在将它们添加到新字符串之前创建两个字符串的副本(创建一个字符串是 O(1))。所以,我们会有加法而不是乘法,不是吗?数组不是一回事(例如,如果我们使用 char 数组)?

你能澄清一下这些观点吗?我不明白我们如何计算复杂度...

【问题讨论】:

    标签: string algorithm time-complexity


    【解决方案1】:

    字符串连接是 O(n) 但在这种情况下它被连接 K 次。 每次您找到一个序列时,您都必须复制整个字符串 + 您找到的内容。例如,如果您在原始字符串中有四个序列 获得最终字符串的成本将是:

    (k-3)+ //first sequence
    (k-3)+(k-2) + //copying previous string and adding new sequence
    ((k-3)+(+k-2)+k(-1) + //copying previous string and adding new sequence
    ((k-3)+(k-2)+(k-1)+k) //copying previous string and adding new sequence
    

    因此复杂度为 O(p + K^2)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-14
      • 2020-09-25
      • 2017-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-24
      相关资源
      最近更新 更多