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.
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.
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<halfLength; i++)
{
char temp = s[i];
s[i] = s[n-1-i];
s[n-1-i] = temp;
}
return new String(s);
}
What is the time complexity of reversing a string?
How to begin Reverse a String algorithm?
Can anyone explain how to reverse a integer number?
Fastest way to reverse a string - and it's not extended string splicing?
Videos
I'm getting ready for an interview and practicing time complexity and I'm ok at recognizing the complexity for the code I've written myself but have a harder time when I throw in methods from the java library.
For example, I read that the method concat was similar to += and that concat time complexity was O(n^2). So if I reverse a string with the code below does that mean my time complexity is O(n^2)? With a space complexity of O(n) since? Where n is the length of the string.
String str="hello"
String s="";
for(int i =str.length()-1; i>=0;i--){
s+=str.substring(i,i+1);
}With this code is the space complexity O(n) and the time complexity O(n)? Where n is the length of the string.
String str="hello";
char[] cArr = str.toCharArray();
int i =0;
int j = cArr.length-1;
char temp;
while(i<j){
temp =cArr[i];
cArr[i]=cArr[j];
cArr[j]=temp;
i++;
j--;
}
str=String.valueOf(cArr);