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

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

    It depends on what you define as "better". :-) Seriously, though; your solution essentially uses the maximum depth of recursion; if stack size is of a concern for your definition of "better", then you'd be better off using something like this:

    public String reverseString(String s) {
       if (s.length() == 1) return s;
       return reverseString(s.substring(s.length() / 2, s.length() -1) + reverseString(0, s.length() / 2);
    }
    

提交回复
热议问题