Created
July 15, 2020 08:54
-
-
Save RP-3/9b795bd51e0a7720ff65607d7085ce89 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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