电竞比分网-中国电竞赛事及体育赛事平台

分享

Leetcode344--翻轉(zhuǎn)字符串

 Coder編程 2020-04-14

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)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
	
	# 建立一個tmp臨時變量,用于緩存數(shù)組著中的元素
	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?1n-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)步

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多