Java – optimal time complexity of string reverse operation: O (n) or O (n / 2)?

The following is a snippet of string inversion

private static String reverseString(String originalString){
char arr[]= originalString.tocharArray();
char temp;

for(int i= 0,j=arr.length-1;i<(arr.length/2);i++,j--){

 temp=arr[i];
 arr[i]=arr[j];
 arr[j]=temp;
}
return new String(arr);

I've seen a lot of discussion about the time complexity of string inversion above, and some of them mentioned that the complexity is O (n / 2) and some o (n)

I want to know which is actually the correct time complexity of string inversion

Any insight will help ease the confusion here

Solution

Asymptotically, there is no difference between O (n) and O (n / 2) The difference between the two is constant

If you want to calculate the exact operand in the above code fragment, it is more accurate to say that it is 3N / 2, because each iteration of the loop contains three operations Of course, you must also add the conversion of the input string to the char array and vice versa, which also require linear time

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>