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

后端 未结 26 2516
一个人的身影
一个人的身影 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);
    }
    
    0 讨论(0)
  • 2020-11-27 15:24

    As Mehrdad noted, it's best not to use recursion. If you do use it, though, you might as well keep both the first and last character each call, thus halving the number of recursive calls. That is,

    public String reverseString(String s){
        int len = s.length();
    
        if (len <= 1) {
            return s;
        }
    
        char fst = s.charAt(0);
        char lst = s.charAt(len - 1);
    
        return lst + reverseString(s.substring(1, len - 2)) + fst;
    }
    

    This also handles the case of the empty string. Perhaps passing along a StringBuilder with the appropriate capacity would speed things up even more, but that's left as an exercise to the reader ;)

    0 讨论(0)
  • 2020-11-27 15:24

    Try the following:

    public class reverse2
    {
        public static void main(String name)
        {
        String revname=new StringBuffer(name).reverse().toString();
        System.out.println("original string " + name + " and the reverse of it is " + revname);
        }
    }
    
    0 讨论(0)
  • 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
                }
            }
    
    0 讨论(0)
  • 2020-11-27 15:27

    In this context, this is totally unnecessary, but you can simulate recursion and avoid recursion depth issues if you make your own stack.

    You can iterative implement recursion, which may be necessary when you have algorithms which are inherently recursive, but also need to run them for big problem sizes.

    String recIterReverse (String word){
    
        Stack <String> stack = new Stack <String> ();
        stack.push(word);
        String result = "";
    
        while (!stack.isEmpty()){
            String temp = stack.pop();
            result = temp.charAt(0) + result;
    
            if (temp.length() > 1){
            stack.push(temp.substring(1));
            }
        }
    
        return result;
    }
    
    0 讨论(0)
  • 2020-11-27 15:29

    Just for the heck of it, here's a tail-recursive method using StringBuilder (which is generally recommended over manipulating Strings).

    public String reverseString(String s_) {
        StringBuilder r = new StringBuilder();
        StringBuilder s = new StringBuilder(s_);
        r = reverseStringHelper(r, s);
        return r.toString();
    }
    private StringBuilder reverseStringHelper(StringBuilder r, StringBuilder s) {
        if (s.length() == 0)
            return r;
        else
            return reverseStringHelper(r.append(s.charAt(0)), s.deleteCharAt(0));
    }
    

    Untested, I haven't dealt with Java in many years, but this should be about right.

    0 讨论(0)
提交回复
热议问题