Whats the best way to recursively reverse a string in Java?

后端 未结 26 2788
一个人的身影
一个人的身影 2020-11-27 14:56

I have been messing around with recursion today. Often a programming technique that is not used enough.

I set out to recursively reverse a string. Here\'s what I cam

26条回答
  •  感情败类
    2020-11-27 15:31

    If you're going to do this, you want to operate on a character array, because a String is immutable and you're going to be copying Strings all over the place if you do it that way.

    This is untested and totally stream of consciousness. It probably has an OB1 somewhere. And very not-Java.

    public String reverseString(String s)
      {
      char[] cstr = s.getChars();
      reverseCStr(cstr, 0, s.length - 1);
    
      return new String(cstr);
      }
    
    /**
     * Reverse a character array in place.
     */
    private void reverseCStr(char[] a, int s, int e)
      {
      // This is the middle of the array; we're done.
      if (e - s <= 0)
        return;
    
      char t = a[s];
      a[s] = a[e];
      a[e] = t;
      reverseCStr(a, s + 1, e - 1);
      }
    

提交回复
热议问题