File tree 1 file changed +49
-2
lines changed
1 file changed +49
-2
lines changed Original file line number Diff line number Diff line change 1
1
# https://leetcode.com/problems/reverse-words-in-a-string-iii/
2
2
3
3
class Solution :
4
- def reverseWords (self , s : str ) -> str :
5
- return ' ' .join ([v [::- 1 ] for v in s .split ()])
4
+ def reverseWords (self , s : str ) -> str :
5
+ # return self.solution1(s)
6
+ # return self.solution3(s)
7
+ return self .solution2 (s )
8
+
9
+ # Time O(n), Space O(n)
10
+ def solution2 (self , s ):
11
+ res = []
12
+ word = []
13
+
14
+ for char in s :
15
+ if char == ' ' :
16
+ res .extend (reversed (word ))
17
+ res .append (' ' )
18
+ word = []
19
+ else :
20
+ word .append (char )
21
+
22
+ res .extend (reversed (word ))
23
+
24
+ return '' .join (res )
25
+
26
+
27
+ # Time O(n), Space O(n)
28
+ def solution1 (self , s ):
29
+ if len (s ) <= 1 :
30
+ return s
31
+
32
+ counter = 0
33
+ res = []
34
+
35
+ def extract_word (from_index , count ):
36
+ for prev in range (count ):
37
+ res .append (s [from_index - prev ])
38
+
39
+ for idx , char in enumerate (s ):
40
+ if char == ' ' :
41
+ extract_word (idx - 1 , counter )
42
+ res .append (' ' )
43
+ counter = 0
44
+ else :
45
+ counter += 1
46
+
47
+ extract_word (len (s ) - 1 , counter )
48
+
49
+ return '' .join (res )
50
+
51
+ def solution3 (self , s ):
52
+ return ' ' .join ([v [::- 1 ] for v in s .split ()])
You can’t perform that action at this time.
0 commit comments