Javascript solution using two pointers


  • 0
    R
    var reverseWords = function(s) {
        var words = s.split(' '),
            first,
            last,
            currentWord,
            temp;
        
        for(var i = 0; i < words.length; i++){
            first = 0;
            currentWord = words[i].split('');
            last = currentWord.length - 1;
            
            while(first <= last){
                temp = currentWord[first];
                currentWord[first] = currentWord[last];
                currentWord[last] = temp;
                first++;
                last--;
            }
            
            words[i] = currentWord.join('');
        }
        
        return words.join(' ');
        
    };

Log in to reply
 

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