Skip to content

Commit fd49745

Browse files
Chris WuChris Wu
Chris Wu
authored and
Chris Wu
committed
add words-in-a-string.py
1 parent 310637a commit fd49745

File tree

2 files changed

+50
-3
lines changed

2 files changed

+50
-3
lines changed

reverse-string.py

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,24 @@
1-
#https://leetcode.com/problems/reverse-string/
1+
"""
2+
Reversing a string is equivalent to
3+
Switch the first and the last, the second and the second last, the third and the third last...
4+
So I use two pointers, 's' at the start, 'e' at the end.
5+
If e and s collapse, the proccess is finished.
6+
7+
(a, b) = (b, a) is equal to
8+
9+
temp = a
10+
a = b
11+
b = temp
12+
13+
For time complexity is O(N), N is the length of the string.
14+
Space complexity is O(1), because I only use pointers and a space to store one char.
15+
"""
216
class Solution(object):
3-
def reverseString(self, s):
4-
return s[::-1]
17+
def reverseString(self, string):
18+
s = 0
19+
e = len(string)-1
20+
while e>s:
21+
(string[s], string[e]) = (string[e], string[s])
22+
s+=1
23+
e-=1
24+
return string

reverse-words-in-a-string.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
"""
2+
I see space as the end of a word.
3+
If a word end I will add it to the left of the output.
4+
That is why I have to add an extra space to the original 's' [0]
5+
Be careful There may be continuous space or space at the start and the end. [1]
6+
The way we combine string, there will be an extra space at the end, so I remove it. [2]
7+
8+
Time complexity is O(N).
9+
Because we loop through the stirng once.
10+
11+
Space complexity is O(N).
12+
Because we use 'opt' to store the output.
13+
"""
14+
class Solution(object):
15+
def reverseWords(self, s):
16+
temp = ''
17+
opt = ''
18+
s = s+' ' #[0]
19+
for c in s:
20+
if c==' ':
21+
if temp is not '': opt = temp+' '+opt #[1]
22+
temp = ''
23+
else:
24+
temp+=c
25+
26+
opt = opt[:-1] #[2]
27+
return opt

0 commit comments

Comments
 (0)