写一个函数,接受一个字符串作为输入,输出反转后的字符串
Example 1:
Input: "hello" Output: "olleh"Example 2:
Input: "A man, a plan, a canal: Panama" Output: "amanaP :lanac a ,nalp a ,nam A"
1:str[::-1]方法
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
return s[::-1]
下面的方法会出现超出时间限制的错误
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
newStr = ""
for i in s:
newStr = i + newStr
return newStr
算法题来自:https://leetcode-cn.com/problems/reverse-string/description/
本文介绍了一种使用Python实现字符串反转的高效方法,通过str[::-1]快速反转字符串,并对比了逐字符拼接法,后者可能因效率低下导致时间限制错误。
773

被折叠的 条评论
为什么被折叠?



