Reverse a string in Java, in O(1)?

后端 未结 10 2012
被撕碎了的回忆
被撕碎了的回忆 2020-12-31 01:47

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

10条回答
  •  臣服心动
    2020-12-31 02:30

    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();
        }
    }
    

提交回复
热议问题