Leetcode344:翻轉字串
編程語言:python
文章目錄
- Leetcode344--翻轉字串
- 題目描述
- 解題思路
Leetcode344–翻轉字串
Leetcode344:翻轉字串
編程語言:python
題目描述
原題鏈接:https://leetcode-cn.com/problems/reverse-string/ (中文)
????? https://leetcode.com/problems/reverse-string/ (英文)
題目描述:
撰寫一個函式,其作用是將輸入的字串反轉過來,輸入字串以字符陣列char[] 的形式給出,
不要給另外的陣列分配額外的空間,你必須原地修改輸入陣列、使用 的額外空間解決這一問題,
你可以假設陣列中的所有字符都是 ASCII碼表中的可列印字符,
示例1:
輸入:[“h”,“e”,“l”,“l”,“o”]
輸出:[“o”,“l”,“l”,“e”,“h”]
示例2:
輸入:[“H”,“a”,“n”,“n”,“a”,“h”]
輸出:[“h”,“a”,“n”,“n”,“a”,“H”]
解題思路
方法1:
使用雙指標方法,從首尾往中間靠攏,相遇時交換完成
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
length = len(s)
half = len(s) // 2
# 建立一個tmp臨時變數,用于快取陣列著中的元素
for i in range(half):
tmp = s[i]
s[i] = s[length-i-1]
s[length-i-1] = tmp
python可以同時給多個變數賦值,上述代碼可以改寫為:
def reverseString(self, s):
"""
:type s: List[str]
:rtype: void Do not return anything, modify s in-place instead.
"""
length = len(s)
half = l//2
for i in range(half):
s[i], s[length-i-1] = s[length-i-1], s[i]
方法2:
使用python內置函式
def reverseString(self, s):
"""
:type s: List[str]
:rtype: void Do not return anything, modify s in-place instead.
"""
s.reverse()
方法3:
使用pop方法,每次回圈洗掉第一元素,然后插入到指定的位置
每次洗掉原字串改變一位,最新的需要翻轉的字符變為第一個字符,回圈次后完成翻轉,
def reverseString(self, s):
"""
:type s: List[str]
:rtype: void Do not return anything, modify s in-place instead.
"""
n = len(s)
for i in range(n-1):
t = s.pop(0)
s.insert(n-i-1, t)
歡迎大家關注我的個人公眾號,同樣的也是和該博客賬號一樣,專注分析技術問題,我們一起學習進步

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/18950.html
標籤:其他
