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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM