【发布时间】:2021-10-23 05:36:45
【问题描述】:
https://leetcode.com/problems/reverse-string/ 嘿,我正在 leetcode 上反转字符串,这就是解决方案。
def reverseString(self, s):
"""
:type s: List[str]
:rtype: None Do not return anything, modify s in-place instead.
"""
s[:] = s[::-1]
我不理解的部分是 s[:]。为什么我们需要那个?根据我的想法,我们可以简单地做:
s = s[::-1]
不明白这一点,希望有人可以指导我。谢谢!
【问题讨论】:
-
请注意已发布代码中的 cmets “.. modify s in-place instead”。正常分配会发生什么不同的事情?另请注意,
s是一个 字符串列表(并且该列表可以修改),它不会修改单个 string“反转字符串”(其中不允许,因为字符串是不可变的)。 -
This answer 准确地解决了这个示例,并附有有用的信息图形。
标签: python