Last active
December 25, 2015 19:59
-
-
Save curiouslychase/7031108 to your computer and use it in GitHub Desktop.
Here's the solution I came up with for this interview question on interviewcake.com: "Write a function to reverse a string in place. 'In place' means 'without creating a new string in memory.'" http://www.interviewcake.com/question/reverse-string-in-place
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
# `ruby reverso.rb "foo"` | |
class Reverso | |
def initialize | |
my_arr = ARGV[0].split("") | |
puts "'#{self.reverso(my_arr)}'" | |
end | |
def reverso my_arr | |
len = my_arr.size - 1 | |
halflen = ((len + 1)/2.0).ceil | |
i = 0 | |
temp = "" | |
my_arr.each do |c| | |
return my_arr.join if i === halflen | |
replaco(my_arr, i, len) | |
len-=1 | |
i+=1 | |
end | |
end | |
def replaco my_arr, i, len | |
temp = my_arr[i] | |
my_arr[i] = my_arr[len] | |
my_arr[len] = temp | |
end | |
end | |
@reverso = Reverso.new |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment