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

后端 未结 26 2799
一个人的身影
一个人的身影 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:35

    There are about 20 answers already but I'll just throw in my recursive algorithm as well. It may be a little verbose but it is at least readable.

    public static String reverseString(String str) {
       return reverseString("", str);
    }
    
    private static String reverseString(String result, String original) {
       if (original.length() == 0) {
          return result;
       } else {
          int length = original.length();
          String lastLetter = original.substring(length - 1, length);
          original = original.substring(0, length - 1);
          return reverseString(result + lastLetter, original);
       }
    }
    

    The code basically recursively takes the end of the string and moves it in front. For example if the string we want to reverse is "jam," then each time the helper method is called, result and original strings are as follows:

    // result:  original:
    // ""       jam
    // m        ja
    // ma       j
    // maj      ""
    

提交回复
热议问题