|
Leetcode344:翻轉(zhuǎn)字符串
編程語言:python
文章目錄
Leetcode344–翻轉(zhuǎn)字符串
Leetcode344:翻轉(zhuǎn)字符串
編程語言:python
題目描述
原題鏈接:https:///problems/reverse-string/ (中文)
????? https:///problems/reverse-string/ (英文)
題目描述:
編寫一個函數(shù),其作用是將輸入的字符串反轉(zhuǎn)過來。輸入字符串以字符數(shù)組char[] 的形式給出。
不要給另外的數(shù)組分配額外的空間,你必須原地修改輸入數(shù)組、使用 O(1) 的額外空間解決這一問題。
你可以假設(shè)數(shù)組中的所有字符都是 ASCII碼表中的可打印字符。
示例1:
輸入:[“h”,“e”,“l(fā)”,“l(fā)”,“o”]
輸出:[“o”,“l(fā)”,“l(fā)”,“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
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內(nèi)置函數(shù)
def reverseString(self, s):
"""
:type s: List[str]
:rtype: void Do not return anything, modify s in-place instead.
"""
s.reverse()
方法3:
使用pop方法,每次循環(huán)刪除第一元素,然后插入到指定的位置
每次刪除原字符串改變一位,最新的需要翻轉(zhuǎn)的字符變?yōu)榈谝粋€字符,循環(huán)n?1次后完成翻轉(zhuǎn)。
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)
歡迎大家關(guān)注我的個人公眾號,同樣的也是和該博客賬號一樣,專注分析技術(shù)問題,我們一起學(xué)習(xí)進(jìn)步
|