Created
March 24, 2017 03:14
-
-
Save jmsevold/38151720f0a2b10793d0cd6c1c616e22 to your computer and use it in GitHub Desktop.
reverse words in a sentence
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
let sentence = "Hello World"; | |
function replaceChar(str,targetIndex,newChar){ | |
return str.substr(0,targetIndex) + newChar + str.substr(targetIndex + 1) | |
} | |
function stringReverser(str, startIndex, endIndex) { | |
if (!str || str.length < 2) { | |
return; | |
} | |
while (startIndex < endIndex) { | |
let tempLeft = str[startIndex]; | |
str = replaceChar(str, startIndex, str[endIndex]); | |
str = replaceChar(str, endIndex, tempLeft); | |
startIndex++; | |
endIndex--; | |
} | |
return str; | |
} | |
function reverseWords(sentence) { | |
// reverse the sentence | |
let str_len = sentence.length; | |
sentence = stringReverser(sentence, 0, str_len - 1); | |
// beginning of our strategy to idenify words | |
let start = 0; | |
let end = 0; | |
while (start < sentence.length) { | |
while (sentence[start] === ' ') { | |
start++; | |
} | |
end = start + 1; | |
while (end < sentence.length && sentence[end] != ' ') { | |
end++; | |
} | |
// having found the beginning and end of a word, we reverse it in place | |
sentence = stringReverser(sentence, start, end - 1); | |
start = end; | |
} | |
return sentence; | |
} | |
let result = reverseWords(sentence) | |
console.log(result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment