Created
April 6, 2018 18:32
-
-
Save bparanj/dd4d1bc50997bbe00a3d6e8cdc8087a5 to your computer and use it in GitHub Desktop.
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
# nil terminating strings are not used in ruby | |
# however for this question assume you are passed a nil terminated string | |
def string_reverse(string, from, to) | |
if (!string || string.length < 2) | |
return | |
end | |
while (from < to) | |
string[from], string[to] = string[to], string[from] | |
from +=1 | |
to -= 1 | |
end | |
string | |
end | |
def reverse_words(sentence) | |
# Here sentence is a nil-terminated string ending with char '\0'. | |
if (!sentence || sentence.length == 0) | |
return | |
end | |
# To reverse all words in the string, we will first reverse | |
# the string. Now all the words are in the desired location, but | |
# in reverse order: "Hello World" -> "dlroW olleH". | |
string_length = sentence.length | |
sentence = string_reverse(sentence, 0, string_length - 1) | |
# Now, s iterate the sentence and reverse each word in place. | |
# "dlroW olleH" -> "World Hello" | |
from = 0 | |
to = 0 | |
while (true) | |
# find the from index of a word while skipping spaces. | |
while (sentence[from] == ' ') | |
from += 1 | |
end | |
if from >= sentence.length | |
break | |
end | |
# find the to index of the word. | |
to = from + 1 | |
while (to < sentence.length && sentence[to] != ' ') | |
to += 1 | |
end | |
# s reverse the word in-place. | |
sentence = string_reverse(sentence, from, to - 1) | |
from = to | |
end | |
sentence | |
end | |
p reverse_words('Hello World!') | |
# "World! Hello" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment