-
Notifications
You must be signed in to change notification settings - Fork 193
/
reverse_words.py
54 lines (44 loc) · 1.62 KB
/
reverse_words.py
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
'''
This problem is taken from Stanford's CS 9: Problem-Solving for the CS Technical Interview.
Question statement:
Reverse all the words in a string of words and spaces / tabs
while preserving the word order and spacing.
Example
'moo cow bark dog' -> 'oom woc krab god'
Potential pitfalls:
Don't reverse the entire string -- preserve the word ordering and the spaces.
We make no guarantee about how many spaces / tabs there are between words,
so you can't split (using the .split() method) and then reverse
the words individually.
My solution:
Start with current word to be None.
Iterate over each character in the string.
+ if it's space/tabs:
+ if the current word is not None, reverse it and add it to result.
+ add current character to the result.
+ else:
+ if the previous character is space/tab, make it the first
character of current word.
+ else, add the current character to the current word
'''
def reverse_string(string):
if len(string) <= 1:
return string
return string[-1] + reverse_string(string[:-1])
def reverse_words(string):
curr_word = ''
results = ''
for char in string:
if char == ' ' or char == '\t':
if not curr_word == '':
results += reverse_string(curr_word)
curr_word = ''
results += char
else:
curr_word += char
results += reverse_string(curr_word)
return results
assert reverse_words('moo cow bark dog') == 'oom woc krab god'
assert reverse_words('moo ') == 'oom '
assert reverse_words(' moo moo') == ' oom oom'
assert reverse_words(' ') == ' '