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

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

    Here is my immutable version:

     String reverse(String str) {
        if(str.length()<2) return str;
        return  reverse(str.substring(1)) +str.charAt(0);
    }
    

    and tail recursive version:

     String reverseTail(String str) {
        if(str.length()<2) return str;
        return str.charAt(str.length()-1)+ reverseTail(str.substring(0,str.length()-1));
    

提交回复
热议问题