Is there any facility in the standard Java libraries that, given a CharSequence, produces the reverse in O(1) time?
I guess this is \"easy\" to implement, just wond
Jon Skeet's solution is likely most efficient. But if you just want a quick and dirty, this should do it and I don't think it would be far behind in performance.
StringBuffer reverse=new StringBuffer(original.toString()).reverse();
A StringBuffer is a CharSequence, so if you're implying that the result must be a CharSequence, this is.
Well, this might be faster than Mr Skeet's solution if you examine the sequence multiple times, as it eliminates the overhead of the calculation to find the right char position every time you read a character. It's going to do it just once per character.
If I was going to do a billion of these, maybe I'd do a benchmark.
Here I have a sample of the same using substring method and o(n). I am aware that using substring will hold complete string memory.
for(int i = 0; i < s.length(); i++) {
s = s.substring(1, s.length() - i) + s.charAt(0) + s.substring(s.length() - i);
System.out.println(s);
}
This might help you. Tell me if I am wrong!!
Well, you can easily produce an implementation of CharSequence
which returns the same length, and when asked for a particular character returns the one at length-index-1
. toString()
becomes O(n) of course...
Creating that reversed CharSequence
would be O(1) - all it's got to do is store a reference to the original CharSequence
, after all. Iterating over all the characters within the sequence is going to be O(n) though, obviously.
Note that creating a reversed CharSequence
(as per the body of your question) is not the same as creating a reversed String
(as per the title of your question). Actually producing the String is O(n), and has to be.
Sample code, mostly untested:
public final class ReverseCharSequence implements CharSequence
{
private final CharSequence original;
public ReverseCharSequence(CharSequence original)
{
this.original = original;
}
public int length()
{
return original.length();
}
public char charAt(int index)
{
return original.charAt(original.length() - index - 1);
}
public CharSequence subSequence(int start, int end)
{
int originalEnd = original.length() - start;
int originalStart = original.length() - end;
return new ReverseCharSequence(
original.subSequence(originalStart, originalEnd));
}
public String toString()
{
return new StringBuilder(this).toString();
}
}
string result = new StringBuffer(yourString).reverse().toString();
Depending on what you understand under O(1) it does not seem possible since even reading the string once needs O(n) with n being the number of characters in the string.