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

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

    You don't want to nest too deeply. Divide-and-conquer is the way to go. Also reduces total size of temporary strings and is amenable to parallelisation.

    public static String reverseString(String str) {
        int len = str.length();
        return len<=1 ? str : (
            reverseString(str.substring(len/2))+
            reverseString(str.substring(0, len/2))
        );
    }
    

    (Not tested - this is stackoverflow.)

    String.concat instead of + would improve performance at the expense of clarity.

    Edit: Just for fun, a tail-recursion friendly version of the naive algorithm.

    public static String reverseString(String str) {
        return reverseString("", str);
    }
    private static String reverseString(String reversed, String forward) {
        return forward.equals("") ? reversed : (
             reverseString(reversed+forward.charAt(0), forward.substring(1)) 
        );
    }
    

    Correct handling of surrogate pairs is left to the interested reader.

提交回复
热议问题