A couple of JavaScript O(n) solutions


  • 0

    We can build the reversed words as if we're using a stack:

    var reverseWords = function(s) {
        let res = '';
        let word = '';
        for (let c of s) {
            if (c === ' ') {
                res += word + c;
                word = '';
            } else {
                word = c + word;
            }
        }
        return res + word;
    };
    

    Or we can do the splitting stuff:

    var reverseWords = function(s) {
        return s.split(' ').map(w => w.split('').reverse().join('')).join(' ');
    };
    

Log in to reply
 

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