-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverseString.py
More file actions
57 lines (47 loc) · 1.1 KB
/
reverseString.py
File metadata and controls
57 lines (47 loc) · 1.1 KB
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
55
56
57
#Source : https://leetcode.com/problems/reverse-string/
#Author : Yuan Wang
#Date : 2018-06-23
'''
**********************************************************************************
*Write a function that takes a string as input and returns the string reversed.
*
*Example:
*Given s = "hello", return "olleh".
**********************************************************************************/
'''
#Pythonic, Time complexity:O(n), Space complexity:O(1)
def reverseString(s):
"""
:type s: str
:rtype: str
"""
return s[::-1]
#Self solution, Time complexity:O(n), Space complexity:O(n)
def reverseString(s):
"""
:type s: str
:rtype: str
"""
result=""
for i in range(len(s)-1,-1,-1):
result+=s[i]
return result
#swap the end element and the front element until the swap ending
def reverseString(s):
"""
:type s: str
:rtype: str
"""
r = list(s)
i, j = 0, len(r) - 1
while i < j:
r[i], r[j] = r[j], r[i]
i += 1
j -= 1
return "".join(r)
#recursion version
def reverseString(s,m = 0,n = len(s)-1):
if n > m:
s[m],s[n] = s[n],s[m]
reverseString(s,m+1,n-1)
print(reverseString("HelloWorld"))