python字符串倒序_Python字符串倒序-7. Reverse Integer

今天做了下LeetCode上面字符串倒序的题目,突然想Python中字符串倒序都有哪些方法,于是网上查了下,居然有这么多种方法:

个人觉得,第二种方法是最容易想到的,因为List中的reverse方法比较常用,做LeetCode题目7. Reverse Integer也用了这种方法,程序耗时65ms

#字符串的反转

#用到for循环的步长参数,从大到小循环,到0为止

defreverse1 (s):

rt= ''

for i in range(len(s)-1, -1, -1):

rt+=s[i]returnrt#用到list的反转函数reverse()

defreverse2 (s):

li=list(s)

li.reverse()

rt= "".join(li)returnrt#用到切片的步长参数,负数代表从右往左遍历

defreverse3 (s):return s[::-1]#用到python内建函数reversed(str)

defreverse4 (s):return "".join(reversed(s))#用到python内建函数reduce()

"""def reduce(function, sequence, initial=None):

reduce(function, sequence[, initial]) -> value

Apply a function of two arguments cumulatively to the items of a sequence,

from left to right, so as to reduce the sequence to a single value.

For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates

((((1+2)+3)+4)+5). If initial is present, it is placed before the items

of the sequence in the calculation, and serves as a default when the

sequence is empty."""

#简单的说就是遍历序列s,放入第一个参数的函数中执行,执行之后结果作为函数的第一个参数,序列的下一个元素作为第二个参数,再次运算

#比如第一次,x='1',y='2';第二次:x='21',y='3';第三次:x='321',y='4'...

from functools importreducedefreverse5 (s):return reduce(lambda x,y:y+x,s)

好奇的是,到底哪个方法运算速度更快呢,于是实验了一下:

9m+gLNRih4kXsB3xXWflY0TxS1HjreYXj1H0wBnjqnUtqXXU+MovZ4aRen1VKqu9HpqFKXXU6PoHxmh4WXccvzeAAAAAElFTkSuQmCC

显然,第三个方法速度最快,也就是利用切片的步长参数。

可见,这个方法比reverse方法更快更方便,且适用于没有reverse方法的字符串和元组。

于是用该方法替换LeetCode第7题的答案:59ms,果然快了一丢丢:)

附LeetCode 7. Reverse Integer代码:

增加了负数和超过int范围的判断,满足leetcode第7题需要:

classSolution(object):defreverse(self, x):""":type x: int

:rtype: int"""y=str(x)

flag=0if '-' ==y[0]:

flag= 1y= y[1:]

result='-'

else:result = ''result+= y[::-1]if int(result) > 2**31-1 or int(result) < 1-2**31 :return0return int(result)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值