From f0514690be7e42772f67c7e098521de94bb8aeb7 Mon Sep 17 00:00:00 2001 From: Shelan Date: Thu, 29 Nov 2018 08:01:44 -0800 Subject: [PATCH] complete --- lib/reverse_words.rb | 44 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/lib/reverse_words.rb b/lib/reverse_words.rb index cb3cc8a..f4ad568 100644 --- a/lib/reverse_words.rb +++ b/lib/reverse_words.rb @@ -1,4 +1,46 @@ # A method to reverse each word in a sentence, in place. + +# time complexity is O(n) b/c it goes through the loop n times based on the length of word inputted. + +# space complexity is O(1) b/c the storage does not increase in size based on the input. + +def string_reverse(my_string, beginning, ending) + front_index = beginning + back_index = ending + + while front_index < back_index + front_value = my_string[front_index] + back_value = my_string[back_index] + + my_string[front_index] = back_value + my_string[back_index] = front_value + + front_index += 1 + back_index -= 1 + end +end +### + def reverse_words(my_words) - raise NotImplementedError + return if my_words == nil + + i = 0 + length = my_words.length + + while i < length + while my_words[i] == ' ' && i < length + i += 1 + end + + beginning = i + + while my_words[i] != ' ' && i < length + i += 1 + end + + ending = i - 1 + + string_reverse(my_words, beginning, ending) + end + return my_words end