简体   繁体   English

时间复杂度O(N ^ 2)在这里如何?

[英]How is the time complexity O(N^2) here?

I already know that the answer to this question is O(N^2) but I am not able to see how. 我已经知道这个问题的答案是O(N^2)但是我不知道如何。 I know the for loop runs N times, but how can it run N^2 times? 我知道for循环运行N次,但是它如何运行N^2次?

public static String rev(String s) {
    String r = "";
    int N = s.length();
    for (int i = 0; i < N; i++) {
        r = s.charAt(i) + r;
    }
    return r;
}

在Java中, String串联r = s.charAt(i) + r在循环中为O(N^2) ,因为Strings是不可变的-在每个串联中都会创建String的新副本。

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

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