gpt4 book ai didi

javascript - 反转字符串中单词的字符顺序

转载 作者:行者123 更新时间:2023-11-29 16:42:00 25 4
gpt4 key购买 nike

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1: Input: "Let's take LeetCode contest" Output: "s'teL ekat edoCteeL tsetnoc"

现在我已经为其编写了以下代码,但它输出,

Output: "s'teL ekat edoCteeL setnoc"

而不是,

Output: "s'teL ekat edoCteeL tsetnoc"

我错过了什么?

/**
* @param {string} s
* @return {string}
*/
var reverseWords = function(s) {
var result="";
var new_word= 0;
for (var i=0; i< s.length; i++)
{
if ((s[i] ==" ") || s[i+1] == undefined)
{
result=result+" "+ s.slice(new_word, i).split("").reverse().join("");;
new_word=i+1;
}
}
return result;
};

最佳答案

使用Array#map的更简洁的解决方案:

var str = "Let's take LeetCode contest";

var output = str.split(" ").map(function(word) {
return word.split('').reverse().join('');
}).join(" ");

console.log(output);

关于javascript - 反转字符串中单词的字符顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44823066/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com