File tree Expand file tree Collapse file tree 2 files changed +50
-3
lines changed Expand file tree Collapse file tree 2 files changed +50
-3
lines changed Original file line number Diff line number Diff line change 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
+ """
2
16
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
Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments