Skip to content

Commit ef2b5c7

Browse files
committed
Create reverse-string.py
1 parent b3398ef commit ef2b5c7

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Python/reverse-string.py

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
# Write a function that takes a string as input and
5+
# returns the string reversed.
6+
#
7+
# Example:
8+
# Given s = "hello", return "olleh".
9+
10+
class Solution(object):
11+
def reverseString(self, s):
12+
"""
13+
:type s: str
14+
:rtype: str
15+
"""
16+
string = list(s)
17+
i, j = 0, len(string) - 1
18+
while i < j:
19+
string[i], string[j] = string[j], string[i]
20+
i += 1
21+
j -= 1
22+
return "".join(string)
23+
24+
25+
# Time: O(n)
26+
# Space: O(n)
27+
class Solution2(object):
28+
def reverseString(self, s):
29+
"""
30+
:type s: str
31+
:rtype: str
32+
"""
33+
return s[::-1]

0 commit comments

Comments
 (0)