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

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

    You can try with an external variable, and add 1 by 1 all chars:

        public static String back="";
    
    public static String reverseString(String str){
    
    
        if(str.length()==0){
    
            return back;
    
        }else {
    
            back+=str.charAt(str.length()-1);
    
            lees(str.substring(0,str.length()-1));
    
    
            return back;
    
        }
    

    }

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

    The best way is not to use recursion. These stuff are usually used to teach students the recursion concept, not actual best practices. So the way you're doing it is just fine. Just don't use recursion in Java for these kind of stuff in real world apps ;)

    PS. Aside what I just said, I'd choose "" as the base case of my recursive function:

    public String reverseString(String s){
        if (s.length() == 0) 
             return s;
    
        return reverseString(s.substring(1)) + s.charAt(0);
    }
    
    0 讨论(0)
  • 2020-11-27 15:38

    here is my recursive reverse function that is working fine

    public static String rev(String instr){
        if(instr.length()<=1){
            return instr;
        } else {
           return (instr.charAt(instr.length()-1)+rev(instr.substring(0,instr.length()-1)) );
        }       
    }
    
    0 讨论(0)
  • 2020-11-27 15:38
    String rev="";
    
    public String reverseString(String s){
            if (s.length()==0) return "";
            return rev+s.substring(s.length()-1,s.length())+reverseString(s.substring(0, s.length()-1));
        }
    
    0 讨论(0)
  • 2020-11-27 15:38

    Reverse String using the recursive method call.

    Sample Code

    public static String reverseString(String s) {
        if (s.length() == 0) {
            return s;
        }
        else {
            return s.charAt(s.length() - 1) + reverseString(s.substring(0, s.length() - 1));
        }
    }
    
    0 讨论(0)
  • 2020-11-27 15:39

    That's definitely how I'd go about recursively reversing a string (although it might be nice to extend it to the case of an empty string in your condition.) I don't think there is any fundamentally better way.

    EDIT: It may be more efficient to operate on a character array and pass a "cutoff" length down the chain of recursion, if you get my drift, rather than making substrings. However, this is not really worth nitpicking about, since it's not a terribly efficient technique in the first place.

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