查找字符串的所有子字符串的复杂性

时间:2013-07-07 09:31:57

标签: java complexity-theory

以下是查找字符串的所有子字符串的解决方案。

for (int i = 0; i < str.length(); i++) {
    String subStr;
    for (int j = i; j < str.length(); j++) {
        subStr = str + str.charAt(j));
        System.out.println(subStr);
    }
}

在互联网上我读到这段代码的复杂性是O(n 2 )。 但是+操作是O(n)操作。 因此,在我看来,复杂性应该是O(n 3 )。

如果我错了,请纠正我的理解。

3 个答案:

答案 0 :(得分:1)

查找字符串的所有子字符串是O(n 2 )(通过查找子字符串我的意思是确定其开始和结束索引),很容易看到,因为子字符串的总数是O( ñ 2 )。

但是将所有这些打印出来都是O(n 3 ),因为要打印的字符总数是O(n 3 )。在您的代码中,println会增加O(n)复杂度(如果正确使用/实现,+运算符应具有O(1)复杂度。)

答案 1 :(得分:0)

向字符串添加字符是O(1)操作。如果您考虑使用println打印输出所需的时间,则可以使用 3

答案 2 :(得分:0)

从字符串中查找所有子字符串的天真方式确实是O(n ^ 2)。但问题中的代码可能不会这样做。这是更正后的版本。

    for (int i = 0; i < str.length(); ++i) {
        //Initialize with max length of the substring 
        StringBuilder prefix = new StringBuilder(str.length() - i);
        for (int j = i; j < str.length(); ++j) {
            prefix.append(str.charAt(j)); //this step is O(1).
            System.out.println(prefix); //this step is supposed to be O(1)
        }
    }

The total number of iterations is given by
Outer Loop  : Inner Loop
First time  : n
Second time : n - 1
Third Time  : n - 2
..
n - 2 time  : 2
n - 1 time  : 1 



So the total number of iterations is sum of iterations of outer loop plus sum of iterations of the inner loop.
n + (1 + 2 + 3 + ... + n - 3 + n - 2 + n - 1 + n) is  = O(n^2)
相关问题