可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.
回答1:
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.
回答2:
The following does not deal with UTF-16 surrogate pairs.
public static String reverse(String orig) { char[] s = orig.toCharArray(); int n = s.length; int halfLength = n / 2; for (int i=0; i
回答3:
You said you don't want to do it the easy way, but for those Googling you should use StringBuilder.reverse:
String reversed = new StringBuilder(s).reverse().toString();
If you need to implement it yourself, then iterate over the characters in reverse order and append them to a StringBuilder. You have to be careful if there are (or can be) surrogate pairs, as these should not be reversed. The method shown above does this for you automatically, which is why you should use it if possible.
回答4:
An old post & question, however still did not see answers pertaining to recursion. Recursive method reverse the given string s, without relaying on inbuilt jdk functions
public static String reverse(String s) { if (s.length()
`
回答5:
The fastest way would be to use the reverse()
method on the StringBuilder
or StringBuffer
classes :)
If you want to implement it yourself, you can get the character array, allocate a second character array and move the chars, in pseudo code this would be like:
String reverse(String str) { char[] c = str.getCharArray char[] r = new char[c.length]; int end = c.length - 1 for (int n = 0; n
You could also run half the array length and swap the chars, the checks involved slow things down probably.
回答6:
I'm not really sure by what you mean when you say you need an efficient algorithm.
The ways of reversing a string that I can think of are (they are all already mentioned in other answers):
Use a stack (your idea).
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).
The thing is that all of them have the same runtime complexity: O(N). Thus it cannot really be argued that any one is any significantly better than the others for very large values of N (i.e. very large strings).
The third method does have one thing going for it, the other two require O(N) extra space (for the stack or the new String), while it can perform swaps in place. But Strings are immutable in Java so you need to perform swaps on a newly created StringBuilder/char[] anyway and thus end up needing O(N) extra space.
回答7:
public class ReverseInPlace { static char[] str=null; public static void main(String s[]) { if(s.length==0) System.exit(-1); str=s[0].toCharArray(); int begin=0; int end=str.length-1; System.out.print("Original string="); for(int i=0; iI think that if you REALLY don't have performance problem you should just go with the most readable solution which is:
StringUtils.reverse("Hello World");
回答9:
If you do not want to use any built in function, you need to go back with the string to its component parts: an array of chars.
Now the question becomes what is the most efficient way to reverse an array? The answer to this question in practice also depends upon memory usage (for very large strings), but in theory efficiency in these cases is measured in array accesses.
The easiest way is to create a new array and fill it with the values you encounter while reverse iterating over the original array, and returning the new array. (Although with a temporary variable you could also do this without an additional array, as in Simon Nickersons answer).
In this way you access each element exactly once for an array with n elements. Thus giving an efficiency of O(n).
回答10:
char* rev(char* str) { int end= strlen(str)-1; int start = 0; while( start
=========================
Wondering how it works?
First operation:
x1 = x1 XOR x2 x1: 1 0 0 x2: 1 1 1 New x1: 0 1 1
Second operation
x2 = x2 XOR x1 x1: 0 1 1 x2: 1 1 1 New x2: 1 0 0 //Notice that X2 has become X1 now
Third operation:
x1 = x1 XOR x2 x1: 0 1 1 x2: 1 0 0 New x1: 1 1 1 //Notice that X1 became X2
回答11:
private static String reverse(String str) { int i = 0; int j = str.length()-1; char []c = str.toCharArray(); while(i
回答12:
I would simply do it this way without a use of any single util function. Just the String class is sufficient.
public class MyStringUtil { public static void main(String[] args) { String reversedString = reverse("StringToReverse"); System.out.println("Reversed String : " + reversedString); } /** * Reverses the given string and returns reversed string * * @param s Input String * @returns reversed string */ private static String reverse(String s) { char[] charArray = s.toCharArray(); // Returns the String's internal character array copy int j = charArray.length - 1; for (int i = 0; charArray.length > 0 && i
Check it. Cheers!!
回答13:
Using String:
String abc = "abcd"; int a= abc.length(); String reverse=""; for (int i=a-1;i>=0 ;i--) { reverse= reverse + abc.charAt(i); } System.out.println("Reverse of String abcd using invert array is :"+reverse);
Using StringBuilder:
String abc = "abcd"; int a= abc.length(); StringBuilder sb1 = new StringBuilder(); for (int i=a-1;i>=0 ;i--) { sb1= sb1.append(abc.charAt(i)); } System.out.println("Reverse of String abcd using StringBuilder is :"+sb1);
回答14:
One variant can be, swapping the elements.
int n = length - 1; char []strArray = str.toCharArray(); for (int j = 0; j
回答15:
public static void main(String[] args){ String string ="abcdefghijklmnopqrstuvwxyz"; StringBuilder sb = new StringBuilder(string); sb.reverse(); System.out.println(sb); }
回答16:
public static String Reverse(String word){ String temp = ""; char[] arr = word.toCharArray(); for(int i = arr.length-1;i>=0;i--){ temp = temp+arr[i]; } return temp; }
回答17:
public static string getReverse(string str) { char[] ch = str.ToCharArray(); string reverse = ""; for (int i = str.Length - 1; i > -1; i--) { reverse += ch[i]; } return reverse; } //using in-built method reverse of Array public static string getReverseUsingBulidingFunction(string str) { char[] s = str.ToCharArray(); Array.Reverse(s); return new string(s); } public static void Main(string[] args) { string str = "123"; Console.WriteLine("The reverse string of '{0}' is: {1}",str,getReverse(str)); Console.WriteLine("The reverse string of '{0}' is: {1}", str, getReverseUsingBulidingFunction(str)); Console.ReadLine(); }
回答18:
Using multiple threads to swap the elements:
final char[] strArray = str.toCharArray(); IntStream.range(0, str.length() / 2).parallel().forEach(e -> { final char tmp = strArray[e]; strArray[e] = strArray[str.length() - e - 1]; strArray[str.length() - e - 1] = tmp; }); return new String(strArray);
回答19:
public static String reverseString(String str) { StringBuilder sb = new StringBuilder(); for (int i = str.length() - 1; i >= 0; i--) { sb.append(str[i]); } return sb.toString(); }