Skip to content

Instantly share code, notes, and snippets.

@RP-3
Created July 15, 2020 08:54
Show Gist options
  • Save RP-3/9b795bd51e0a7720ff65607d7085ce89 to your computer and use it in GitHub Desktop.
Save RP-3/9b795bd51e0a7720ff65607d7085ce89 to your computer and use it in GitHub Desktop.
/**
* @param {string} s
* @return {string}
*/
// snazzy one liner
// o(n) time + o(n) space
var reverseWords = function(s) {
return s.trim().replace(/\s\s+/g, ' ').split(' ').reverse().join(' ');
};
// theoretically o(1) space, o(n) time
var reverseWords = function(s) {
const sen = [];
let i = 0;
for(i=0; i<s.length && s[i] === ' '; i++); // ignore starting spaces
for(; i<s.length; i++){ // but from the first real character
if(s[i-1] === ' ' && s[i] === ' ') continue; // always ignoring consecutive spaces
sen.push(s[i]); // push the entire sentence
}
while(sen.length && sen[sen.length-1] === ' ') sen.pop(); // pop trailing spaces
sen.reverse(); // now reverse the entire sentence
let [l, r] = [0, 0]; // then reverse individual words
while(r < sen.length){
if(sen[r] === ' '){ // if we arrive at a space
reverse(l, r-1, sen); // reverse everything preceding
l = r+1; // and init the left boundary of the next word
}
r++;
}
reverse(l, sen.length-1, sen); // and reverse the last word
return sen.join('');
};
function reverse(l, r, array){
while(l < r){
[array[l], array[r]] = [array[r], array[l]];
l++; r--;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment