JavaScript solution using map/split/reverse/join


  • 0
    var reverseWords = function(s) {
        let words = s.split(' ');
        let result = ''
        words = words.map(word => {
            return word.split('').reverse().join('')
        });
        
        result = words.join(' ');
        
        return result;
    };
    

    Take the example input for explanation
    "Let's take LeetCode contest"
    First we split the input into an words array
    ['Let's', 'take', 'LeetCode', 'contest']

    Next, we map the words array and split each word again
    For the first round, we have
    ['L', 'e', 't', ''', 's']
    then we can use array built-in function reverse() to get
    ['s', ''', 't', 'e', 'L']
    finally, we join these character to get the expected result

    That's all~~


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.