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

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

    StringBuffer has a reverse: http://java.sun.com/j2se/1.4.2/docs/api/java/lang/StringBuffer.html#reverse()

    BTW, I assume you meant O(n) because O(1) (as other people have mentioned) is obviously impossible.

    0 讨论(0)
  • 2020-12-31 02:17

    // worked hard to figure this out

    public static String ReverseString(String s){
        if (s.length()>0){
            s=s.charAt(s.length()-1)+printString(s.substring(0,s.length()-1));
        }
        return s;
    }
    
    0 讨论(0)
  • 2020-12-31 02:20

    How all the others wrote already, it's not possible in O(1) time, since you do have to look at least at every character once.

    But if you meant how to do it in O(1) space, here's it: If you want to do it in O(1) space, you can obviously not allocate a new string of the same length, but you have to swap the characters in-place.

    So all you have to do is iterate from left to the middle of the string and simultaneously from right to the middle and swap elements. Pseudocode (Conventions: Let string s be accessible at the n-th character via s[n]. If s has length k, we say it has elements 0 to k-1):

    for i=0; i<len(s)/2; ++i{
     char tmp = s[i]
     s[i] = s[len(s)-1-i]
     s[len(s)-1-i] = tmp
    }
    

    So you see, all you need is a auxiliary variable tmp containing your current char for swapping it, so you can do it in O(1) space.

    0 讨论(0)
  • 2020-12-31 02:21

    This is impossible. In order to reverse a string you must process each character at least once, thus, it must be at least O(n).

    0 讨论(0)
  • 2020-12-31 02:22
    for (count = str.length()-1; count >= 0; count--) {
         tempStr = tempStr.concat(Character.toString(origStr.charAt(count)));
    }
    
    0 讨论(0)
  • 2020-12-31 02:26

    Better yet use StringBuilder to reverse, which is the non-synchronized version of StringBuffer.

    0 讨论(0)
提交回复
热议问题