344. Reverse String

题目描述:

Write a function that reverses a string. The input string is given as an array of characters char[].

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

You may assume all the characters consist of printable ascii characters.

 

Example 1:

Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

Example 2:

Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]

代码实现(个人版):

 1 class Solution:
 2     def reverseString(self, s) -> None:
 3         """
 4         Do not return anything, modify s in-place instead.
 5         """
 6         s[:] = s[::-1]
 7 
 8 if __name__ == '__main__':
 9     x = ['h','e','l','l','o']
10     y = Solution().reverseString(x)
11     print(x)

注:代码可能会提示“Assigning result of a function call, where the function has no returnpylint(assignment-from-no-return)”,不用管它,因为题目明确要求不能返回任何对象,而且这个代码是可以运行的。

 

如果是单纯地完成列表中字符串的反转,则只需要

s = s[::-1]

即可。但这里要注意一个问题:局部变量和全局变量的内存地址是相互独立的。在上面那段代码中,x = ['h','e','l','l','o'] 是全局变量,而 s 只是一个局部变量,s = s[::-1]只是对局部变量s进行了修改,并不影响全局变量x的值,此时调用函数后,最终输出的仍为x = ['h','e','l','l','o']。

要想实现对全局变量的修改,在函数内部对局部变量进行修改时,必须加上局部变量的索引,这个时候相当于是对局部变量指向的地址中的内容进行修改,也就是对全局变量进行修改,这样才能在不进行return的情况下对全局变量x进行反转。

参考文献:

[1] 在函数里面修改列表数据:https://blog.csdn.net/u010969910/article/details/82764372

上一篇:输入框,手机号输入,344格式(jQuery和Vue)


下一篇:344、345 反转字符串