Created
July 22, 2019 09:01
-
-
Save kylejeske/3c9a7dc06acc826018bcec90fd71cfd7 to your computer and use it in GitHub Desktop.
Reverse words in place
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
/** | |
* Your team is scrambling to decipher a recent message, worried it's a plot to break into a major European National Cake Vault. | |
* The message has been mostly deciphered, but all the words are backward! Your colleagues have handed off the last step to you. | |
* | |
* Write a function reverseWords() that takes a message as a string and reverses the order of the words in place. | |
* | |
* string message = "cake pound steal"; | |
* reverseWords(message); | |
* cout << message << endl; | |
* // prints: "steal pound cake" | |
*/ | |
let reverseWords = (str="") => { | |
let words = str.split(" "); | |
// built-in approach | |
// words = words.reverse(); | |
// words = output.join(" "); | |
// return words; | |
// or.. with out using another data structure | |
str = ""; | |
for (let i=(words.length-1); i >= 0; i--) { | |
str += words[i]; | |
if (i != 0) { | |
str += " "; | |
} | |
} | |
return str; | |
} | |
const runner = () => { | |
console.log(`Expecting: 'steal pound cake'; Answer? ${reverseWords("cake pound steal")}`); | |
}; | |
runner(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment