Skip to content

Instantly share code, notes, and snippets.

@dashsaurabh
Last active January 25, 2020 02:36
Show Gist options
  • Save dashsaurabh/e46ddeeaf13722e9e949fa888df5d6e8 to your computer and use it in GitHub Desktop.
Save dashsaurabh/e46ddeeaf13722e9e949fa888df5d6e8 to your computer and use it in GitHub Desktop.
Reverse Individual Words in a String
/**
* @param {string} s
* @return {string}
* "Let's take LeetCode contest" printed as "s'teL ekat edoCteeL tsetnoc"
*/
var reverseWords = function(s) {
let sentence = [];
let word = [];
for(let i=0;i<s.length;i++) {
if (s.charAt(i) !== " ") {
word.push(s.charAt(i));
}else{
sentence.push(reverseWord(word));
word = [];
}
}
sentence.push(reverseWord(word))
return sentence.join(' ')
};
var reverseWord = function(word){
let stack = [];
let reversedWord = [];
for(let i=0;i<word.length;i++) {
stack.push(word[i]);
}
while(stack.length !== 0) {
reversedWord.push(stack.pop())
}
reversedWord = reversedWord.join('')
return reversedWord;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment