Last active
January 25, 2020 02:36
-
-
Save dashsaurabh/e46ddeeaf13722e9e949fa888df5d6e8 to your computer and use it in GitHub Desktop.
Reverse Individual Words in a String
This file contains 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} | |
* "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