简体   繁体   English

下面程序的时间复杂度是多少?

[英]What's the time complexity of below program?

What's the time complexity of this program?这个程序的时间复杂度是多少? We calculate time complexity based on arbitrarily large input.我们根据任意大的输入计算时间复杂度。 In this example, the input string can be really huge but if it will not have spaces then it's just O(n).在这个例子中,输入字符串可能非常大,但如果它没有空格,那么它只是 O(n)。 In case if the string has spaces it's going to be O(n * numberOfWords), can I consider this as O(n^2) time complexity?如果字符串有空格,它将是 O(n * numberOfWords),我可以将其视为 O(n^2) 时间复杂度吗? Thank you in advance!先感谢您!

    public static String revEachWord(String str) {
        String reversed = "";
        String[] words = str.split(" ");
        
        for(String word : words) {
            String reversedWord = "";
            for(int i = word.length() - 1; i >= 0; i--) {
                reversedWord += word.charAt(i);
            }

            reversed += reversedWord + " ";
        }
        
        return reversed.trim();
    }

Aleksey pointed out that it's O(numberOfWords * averageWordLength) . Aleksey指出它是O(numberOfWords * averageWordLength) This is correct (if we ignore += for a moment), but a more general answer would be in terms of the length of the input, n .这是正确的(如果我们暂时忽略+= ),但更一般的答案是输入的长度n Since n = numberOfWords * averageWordLength , we can say that it's O(n) , or linear.由于n = numberOfWords * averageWordLength ,我们可以说它是O(n)或线性的。

But that's not quite right.但这并不完全正确。 As chrylis pointed out in a comment, since you're using += to build your string, it would take much longer: O(n) for each copy and numberOfWords total copies, for O(n * numberOfWords) total, or O(n^2) in the worst case.正如chrylis在评论中指出的那样,由于您使用+=来构建字符串,因此需要更长的时间:每个副本的O(n)numberOfWords总副本,对于O(n * numberOfWords)总计,或O(n^2)在最坏的情况下。 (It might be even worse than that, actually; I haven't factored in the += in the nested loop.) Yikes. (实际上,它可能比这更糟;我没有考虑嵌套循环中的+= 。)哎呀。 Better start using StringBuilder to get that nice O(n) running time.最好开始使用StringBuilder以获得良好的O(n)运行时间。

O(numberOfWords * averageWordLength) O(numberOfWords * averageWordLength)

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

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