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

后端 未结 10 2024
被撕碎了的回忆
被撕碎了的回忆 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:28

    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.

提交回复
热议问题