344. Reverse String
Description
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = “hello”, return “olleh”.
Code
class Solution(object):
def reverseString(self, s):
“””
:type s: str
:rtype: str
“””
length = len(s)
if length < 2:
return s
strings_lst = []
for i in reversed(range(0,length)):
strings_lst.append(s[i])
return ‘’.join(strings_lst)
Python
reversed() Parameters
The reversed() method takes a single parameter:
seq - sequence that should be reversed
Could be an object that supports sequence protocol (len() and getitem() methods) as tuple, string, list or range
Could be an object that has implemented reversed()1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21# for string
seqString = 'Python'
print(list(reversed(seqString)))
# for tuple
seqTuple = ('P', 'y', 't', 'h', 'o', 'n')
print(list(reversed(seqTuple)))
# for range
seqRange = range(5, 9)
print(list(reversed(seqRange)))
# for list
seqList = [1, 2, 4, 3, 5]
print(list(reversed(seqList)))
# result:
['n', 'o', 'h', 't', 'y', 'P']
['n', 'o', 'h', 't', 'y', 'P']
[8, 7, 6, 5]
[5, 3, 4, 2, 1]