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

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

    This is my solution,I saw in many solutions above we are getting the string length but ideally we don't need that. The Zen is to use recursion, just chop the first char of string and pass the rest to recursive method. Yay!! we got the solution.

    private static void printReverse(String str) {
                if (!str.isEmpty()) {
                    String firstChar = str.substring(0, 1); //Get first char of String
                    String newstr = str.substring(0, 0) + str.substring(1); // Get remaining string
                    printReverse(newstr); // Recursion magic
                    System.out.print(firstChar); //Output
                }
            }
    

提交回复
热议问题