简体   繁体   中英

Reverse order of characters of words in string

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"

Now I have written the below code for it but it outputs,

Output: "s'teL ekat edoCteeL setnoc"

Instead of,

Output: "s'teL ekat edoCteeL tsetnoc"

What am I missing?

/**
 * @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;
};

A much cleaner solution using 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); 

You can do it using Array#map

 function reverseWords (str) { return str.split(" ") .map(function (word) { return word.split("").reverse().join("") }) .join(" "); } console.log(reverseWords("Let's take LeetCode contest")); // s'teL ekat edoCteeL tsetnoc 

You could handle it with a simple one-liner.

 const reverse = (s) => s.split(' ').map(v => v.split('').reverse().join('')).join(' '); console.log(reverse("Let's take LeetCode contest")); 

Basically you try to test a position, which has the wrong index.

if (s[i] === " " || s[i + 1] === undefined) {
//                    ^^^^^

You need to check the value at the index and decide if a word is found. In this case it's the last word. To reach that word without changing to mutch of the code is to loop one position over the last index and check then. In this case the last word has the right length and you can reverse it.

 var reverseWords = function (s) { var result = ""; var new_word = 0; for (var i = 0; i <= s.length; i++) { // ^^ loop over length if (s[i] === " " || !s[i]) { // ^ check at index result += s.slice(new_word, i).split("").reverse().join("") + (s[i] ? ' ' : ''); // ^^^^^^^^^^^^^^^^^ // apply space // only inbetween new_word = i + 1; } } return result; }; console.log(reverseWords("Let's take LeetCode contest" )); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

If you like an ES6 version, you could use some spread syntax ... for getting single characters in an array.

 var string = "Let's take LeetCode contest", reversed = string.split(' ').map(w => [...w].reverse().join('')).join(' '); console.log(reversed); 

 var word="Let's take LeetCode contest"; var reversedWord=""; var arr=word.split(' '); for(i=0;i<arr.length;i++){ reversedWord+=arr[i].split('').reverse().join(''); reversedWord+=" "; } console.log(reversedWord); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM