[leetcode]Python实现-344.反转字符串

344.反转字符串

描述

请编写一个函数,其功能是将输入的字符串反转过来。

示例

输入:s = “hello”
返回:”olleh”

class Solution:
    def reverseString(self, s):
        """
        :type s: str
        :rtype: str
        """
        l = list(s)[::-1]
        res = ''.join(l)
        return res

这题用到之前总结的字符串与列表的互相转换。

字符串与列表相互转换

字符串转列表:
方法1-split()

>>> s = 'a b c d'
>>> s.split(' ')
['a', 'b', 'c', 'd']

方法2-list()

>>> s = 'abcd'
>>> list(s)
['a', 'b', 'c', 'd']

方法3-eval()函数(该方法也可用于转换dict、tuple等)

>>> s
'[1,2,3]'
>>> eval(s)
[1, 2, 3]
>>> type(eval(s))
<class 'list'>

列表转字符串:
string = ”.join(l) 前提是list的每个元素都为字符

别人的

    return s[::-1]

猜你喜欢

转载自blog.csdn.net/qq_34364995/article/details/80715445
今日推荐