Recursive string reversal function in javascript?

前端 未结 12 1492
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 08:48

I\'m a pretty experienced frontend engineer with a weak CS background. I\'m trying to get my head around the concept of recursion. Most of the examples and purported explana

相关标签:
12条回答
  • 2020-12-03 09:05

    A 25% faster function: jsperf.com

    function Reverse(str) {
      if (str === null) {
        return null;
      }
      if (str.length <= 1) {
        return str;
      }
      var first = str[0];
      var last = str[str.length - 1];
      var str1 = Reverse(str.substring(1, str.length - 1));
      return last + str1 + first;
    }
    
    var result = Reverse("a really serious string of nothingness making call stack to explode");

    0 讨论(0)
  • 2020-12-03 09:06

    So far the best I think:

    function reverse(s) {
        if (s.length===1) return s;
        return reverse(s.slice(1)) + s[0];
    }
    
    0 讨论(0)
  • 2020-12-03 09:10

    This is a pretty straightforward C# implementation of the algorithm you asked for. I think it could be rewritten in javascript pretty easily.

    /*
    C#: The Complete Reference 
    by Herbert Schildt 
    
    Publisher: Osborne/McGraw-Hill (March 8, 2002)
    ISBN: 0072134852
    */
    
    
    // Display a string in reverse by using recursion. 
    
    using System; 
    
    class RevStr { 
    
      // Display a string backwards. 
      public void displayRev(string str) { 
        if(str.Length > 0)  
          displayRev(str.Substring(1, str.Length-1)); 
        else  
          return; 
    
        Console.Write(str[0]); 
      } 
    } 
    
    public class RevStrDemo { 
      public static void Main() {   
        string s = "this is a test"; 
        RevStr rsOb = new RevStr(); 
    
        Console.WriteLine("Original string: " + s); 
    
        Console.Write("Reversed string: "); 
        rsOb.displayRev(s); 
    
        Console.WriteLine(); 
      } 
    }
    
    0 讨论(0)
  • 2020-12-03 09:11

    Try this:

    function recurse(s) {  
      if (s.length == 0) {  
        return '' // stopping condition  
      } else {  // return last char + result of function called with chars up to last char  
        return s.substring(s.length, s.length -1) + recurse(s.substring(0, s.length -1))  
      }
    }  
    
    0 讨论(0)
  • 2020-12-03 09:14

    One line of code using ternary operators you can easily reverse it.

    Explanation: if string exists (if not null) then return recursion otherwise stop the recursion.

      function reverseString(str) {
        return (str ? reverseString(str.substring(1)) + str.charAt(0) : str);
      }
    

    Function call:

    console.log(reverseString('hello'));
    
    0 讨论(0)
  • 2020-12-03 09:19
    function reverse(str) {
      if(str.charAt(0) === ''){
        return "";
      }
      return str.charAt(str.length -1) + reverse(str.substring(0,str.length-1));
    }
    
    0 讨论(0)
提交回复
热议问题