Home > database >  557. Reverse Words in a String III javascript (spacing issue)
557. Reverse Words in a String III javascript (spacing issue)

Time:02-20

I'm solving a problem (leetcode 557) Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

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

Example 2:

Input: s = "God Ding"
Output: "doG gniD"

When I write the solution below this way I get a wrong answer which is not reversed.

var reverseWords = function(s) {
    let separate = s.split("");
    let res = separate.map((str) => {
        return str.split("").reverse().join("");
    });

    return res.join("")
};

But when I write as shown below my answer is accepted

var reverseWords = function(s) {
    let separate = s.split(" ");
    let res = separate.map((str) => {
        return str.split("").reverse().join("");
    });

    return res.join(" ")
};

I am really confused about how the spacing in quotation marks of the second and last line of code is affecting the solution. Thanks in advance

CodePudding user response:

s.split("") will find every occurrence of an emtpy string, which is literally between every pair of consecutive characters. So it splits the original string into individual characters. The documentation on mdn has a specific mention of this case:

If separator is an empty string (""), str is converted to an array of each of its UTF-16 "characters".

s.split(" ") will find every occurrence of a space, which has much fewer occurrences of course, and it will split your original string into words.

  • Related