Reverse Sentence
excerpt: This covers the basic building block two pointers.
tags: two-pointers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
| def reverse(sentence)
reverser(sentence, 0, sentence.length-1)
from = 0
to = 0
loop do
while (sentence[from] == ' ')
from+=1
end
break if from >= sentence.length
to = from + 1
while (to < sentence.length && sentence[to] != ' ')
to += 1
end
sentence = reverser(sentence, from, to - 1)
from = to
end
return sentence
end
def reverser(s, from, to)
return s if s.length < 2
while from < to
s[from], s[to] = s[to], s[from]
from += 1
to -= 1
end
s
end
p reverse('The quick brown fox jumped over the lazy dog.')
|