[英]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.