#344 reverse string
2018-04-23 本文已影响3人
万事屋银酱
Write a function that takes a string as input and returns the string reversed.
Example: Given s = "hello", return "olleh".

我是从string类型开始做起的。这个题目的算法非常简单,把给定字符逆序重新排列即可,我一开始的想法是:

但是当提交后发现Time limit exceeded(TLE)的问题,后来发现了上面的第一种更为优化的方法。因为在Python中的字符串是不能修改的,因此第10行中每次给ans字符串赋值都是在新建一个字符串。其实Python对于字符串提供了很好的切割功能(slicing),可以在原有字符串上面对所需要的字符进行切割重组,通常这么定义:s[start:stop:step]
又在网上看到了一个递归的方法,很有意思
