Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient algorithm for reversing a String in Java?

What is the most efficient way to reverse a string in Java? Should I use some sort of xor operator? The easy way would be to put all the chars in a stack and put them back into a string again but I doubt that's a very efficient way to do it.

And please do not tell me to use some built in function in Java. I am interested in learning how to do it not to use an efficient function but not knowing why it's efficient or how it's built up.

like image 671
Hultner Avatar asked Mar 13 '10 16:03

Hultner


People also ask

What is efficient way to reverse String in Java?

The easiest way to reverse a string in Java is to use the built-in reverse() function of the StringBuilder class.

How do you reverse a String efficiently?

Create a new reversed String by adding characters one by one in reverse order from the original String to a blank String/StringBuilder/char[]. Exchange all characters in the first half of the String with its corresponding position in the last half (i.e. the ith character gets swapped with the (length-i-1)th character).

Is there any method to reverse a String in Java?

String class in Java does not have reverse() method, however, the StringBuilder class has built-in reverse() method.

Which data structures is the better one to reverse this String?

Another data structure to be used to reverse the string is stack. A most common example to understand the stack data structure is the bunch of the plates we normally see.


1 Answers

You say you want to know the most efficient way and you don't want to know some standard built-in way of doing this. Then I say to you: RTSL (read the source, luke):

Check out the source code for AbstractStringBuilder#reverse, which gets called by StringBuilder#reverse. I bet it does some stuff that you would not have considered for a robust reverse operation.

like image 66
Tom Avatar answered Oct 06 '22 00:10

Tom