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

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

    In Java, since the String is immutable, the String concatenation would be more complex than it looks like.

    For every concatenation, it creates a new string copying the contents of original String resulting in a linear complexity O(n) where n is the length of the string, so for m such operations it is O(m*n), we can say it is of quadratic complexity O(n^2).

    We can use a StringBuilder which has O(1) complexity for each append. Below is the recursive program using StringBuilder. This uses only n/2 stack frames, so it has less space complexity than the normal recursive call which would be like s.charAt(s.length-1) + reverse(s.subString(0, s.length-2);

    public class StringReverseRecursive {
        public static void main(String[] args) {
            String s = "lasrever gnirts fo noitatnemelpmi evisrucer a si sihT";
            StringBuilder sb = new StringBuilder(s);
            reverse(s, sb, 0, sb.length() - 1);
            System.out.println(sb.toString());
        }
    
        public static void reverse(String s, StringBuilder sb, int low, int high) {
            if (low > high)
                return;
            sb.setCharAt(low, s.charAt(high));
            sb.setCharAt(high, s.charAt(low));
            reverse(s, sb, ++low, --high);
        }
    }
    

提交回复
热议问题