您的位置:首页 > 编程语言 > Python开发

leetcode 344 python

2017-02-22 20:27 423 查看
Write a function that takes a string as input and returns the string reversed.

Example:

Given s = "hello", return "olleh".

Subscribe to see which companies asked this question

class Solution(object):

    def reverseString(self, s):

        """

        :type s: str

        :rtype: str

        """

        b = list(s)

        c = len(s)

        print("%d",c)

        d = []

        j = -1

        for i in range(1,c+1):

            d.append(s[j])

            j = j -1

        str_convert = ''.join(d)

        return str_convert

因为python的read和write方法的操作对象都是string。而操作二进制的时候会把string转换成list进行解析,解析后重新写入文件的时候,还得转换成string。

>>> import string

>>> str = 'abcde'

>>> list = list(str)

>>> list

['a', 'b', 'c', 'd', 'e']

>>> str

'abcde'

>>> str_convert = ''.join(list)

>>> str_convert

'abcde'

class
Solution(object):
def reverseString(self, s):

            """ :type s: str :rtype: str """

            return s[::-1]

所有数,每5个取一个:

>>> L[::5]
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]

甚至什么都不写,只写
[:]
就可以原样复制一个list:

>>> L[:]
[0, 1, 2, 3, ..., 99]

tuple也是一种list,唯一区别是tuple不可变。因此,tuple也可以用切片操作,只是操作的结果仍是tuple:

>>> (0, 1, 2, 3, 4, 5)[:3]
(0, 1, 2)

字符串
'xxx'
也可以看成是一种list,每个元素就是一个字符。因此,字符串也可以用切片操作,只是操作结果仍是字符串:

>>> 'ABCDEFG'[:3]
'ABC'
>>> 'ABCDEFG'[::2]
'ACEG'


        s1 = list(s)

        s1.reverse()

        return ''.join(s1)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: