在JavaScript中反转线性的三种方法

本文介绍了在JavaScript中反转字符串的三种方法:使用内置函数(split-reverse-join)、递减for循环以及递归。每种方法都有详细的解释和示例代码。递归方法在字符串过长时可能导致性能问题。这是一个常见的算法问题,常出现在技术面试中。
摘要由CSDN通过智能技术生成

本文基于免费的代码营基本算法脚本“ 反转字符串 ”

采访者可能会要求您编写不同的方式来转换串行,或者他们可能会要求您不使用内置方法来转换串行,甚至会要求您使用递归归转换字符串。

可能有几十种不同的方法可以执行此操作,但内置反向功能除外,因为JavaScript没有。

以下是我解决JavaScript中的串行反转问题的三种最有趣的方法。

算法挑战

反转提供的纱线。

您可能需要将字符串转换为层叠,然后才能将其反转。

您的结果必须是字符串。

function reverseString(str) {
    return str;
}
reverseString("hello");

提供的测试示例

  • reverseString(“ hello”)应该变成“ olleh”
  • reverseString(“ Howdy”)应该变成“ ydwoH”
  • reverseString(“Greetings from Earth”)应该返回“ htraE morf sgniteerG”

1.使用内置函数反转字符串

对于此解决方案,我们将使用三种方法:String.prototype.split()方法,Array.prototype.reverse()方法和Array.prototype.join()方法。

  • split()方法通过将字符串对象拆分为子字符串,将String对象拆分为字符串数组。
  • reverse()方法将数组反转到位。第一个数组元素变为最后一个,最后一个数组变为第一个。
  • join()方法将数组的所有元素连接到字符串中。
function reverseString(str) {
    // Step 1. Use the split() method to return a new array
    var splitString = str.split(""); // var splitString = "hello".split("");
    // ["h", "e", "l", "l", "o"]
 
    // Step 2. Use the reverse() method to reverse the new created array
    var reverseArray = splitString.reverse(); // var reverseArray = ["h", "e", "l", "l", "o"].reverse();
    // ["o", "l", "l", "e", "h"]
 
    // Step 3. Use the join() method to join all elements of the array into a string
    var joinArray = reverseArray.join(""); // var joinArray = ["o", "l", "l", "e", "h"].join("");
    // "olleh"
    
    //Step 4. Return the reversed string
    return joinArray; // "olleh"
}
 
reverseString("hello");

将这三种方法链接在一起:

function reverseString(str) {
    return str.split("").reverse().join("");
}
reverseString("hello");

2.用递减的For循环反转字符串

function reverseString(str) {
    // Step 1. Create an empty string that will host the new created string
    var newString = "";
 
    // Step 2. Create the FOR loop
    /* The starting point of the loop will be (str.length - 1) which corresponds to the 
       last character of the string, "o"
       As long as i is greater than or equals 0, the loop will go on
       We decrement i after each iteration */
    for (var i = str.length - 1; i >= 0; i--) { 
        newString += str[i]; // or newString = newString + str[i];
    }
    /* Here hello's length equals 5
        For each iteration: i = str.length - 1 and newString = newString + str[i]
        First iteration:    i = 5 - 1 = 4,         newString = "" + "o" = "o"
        Second iteration:   i = 4 - 1 = 3,         newString = "o" + "l" = "ol"
        Third iteration:    i = 3 - 1 = 2,         newString = "ol" + "l" = "oll"
        Fourth iteration:   i = 2 - 1 = 1,         newString = "oll" + "e" = "olle"
        Fifth iteration:    i = 1 - 1 = 0,         newString = "olle" + "h" = "olleh"
    End of the FOR Loop*/
 
    // Step 3. Return the reversed string
    return newString; // "olleh"
}
 
reverseString('hello');

没有注释:

function reverseString(str) {
    var newString = "";
    for (var i = str.length - 1; i >= 0; i--) {
        newString += str[i];
    }
    return newString;
}
reverseString('hello');

3.递归反转字符串

对于此解决方案,我们将使用两种方法:String.prototype.substr()方法和String.prototype.charAt()方法。

  • substr()方法以指定的字符数返回从指定位置开始的字符串中的字符。
"hello".substr(1); // "ello"
  • charAt()方法从字符串中返回指定的字符。
"hello".charAt(0); // "h"

递归的深度等于String的长度。如果String太长且堆栈大小是主要问题,则此解决方案不是最佳解决方案,并且会非常慢。

function reverseString(str) {
  if (str === "") // This is the terminal case that will end the recursion
    return "";
  
  else
    return reverseString(str.substr(1)) + str.charAt(0);
/* 
First Part of the recursion method
You need to remember that you won’t have just one call, you’ll have several nested calls

Each call: str === "?"                            reverseString(str.subst(1))     + str.charAt(0)
1st call – reverseString("Hello")   will return   reverseString("ello")           + "h"
2nd call – reverseString("ello")    will return   reverseString("llo")            + "e"
3rd call – reverseString("llo")     will return   reverseString("lo")             + "l"
4th call – reverseString("lo")      will return   reverseString("o")              + "l"
5th call – reverseString("o")       will return   reverseString("")               + "o"

Second part of the recursion method
The method hits the if condition and the most highly nested call returns immediately

5th call will return reverseString("") + "o" = "o"
4th call will return reverseString("o") + "l" = "o" + "l"
3rd call will return reverseString("lo") + "l" = "o" + "l" + "l"
2nd call will return reverserString("llo") + "e" = "o" + "l" + "l" + "e"
1st call will return reverserString("ello") + "h" = "o" + "l" + "l" + "e" + "h" 
*/
}
reverseString("hello");

没有注释:

function reverseString(str) {
  if (str === "")
    return "";
  else
    return reverseString(str.substr(1)) + str.charAt(0);
}
reverseString("hello");

条件(Ternary)运算符:

function reverseString(str) {
  return (str === '') ? '' : reverseString(str.substr(1)) + str.charAt(0);
}
reverseString("hello");

在JavaScript中反转字符串是一种小型且简单的算法,可以在电话技术筛选或技术面试中询问。您可以采用短路径来解决此问题,也可以采用递归或更复杂的解决方案来解决。

关注微信公众号:知柯信息安全 获取更多资讯
文章:Sonya Moisset
排版:知柯-匿名者

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

知柯信安

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值