哪有做企業(yè)網(wǎng)站seo關(guān)鍵詞排名優(yōu)化品牌
今天是代碼隨想錄的第七天,寫了力扣的151.翻轉(zhuǎn)字符串里的單詞;
之后或許還要再琢磨琢磨
代碼隨想錄鏈接
力扣鏈接
151.翻轉(zhuǎn)字符串里的單詞,代碼如下:
# class Solution:
# def reverseWords(self, s: str) -> str:
# # Solution1
# (版本一)先刪除空白,然后整個(gè)反轉(zhuǎn),最后單詞反轉(zhuǎn)。 因?yàn)樽址遣豢勺冾愋?#xff0c;所以反轉(zhuǎn)單詞的時(shí)候,需要將其轉(zhuǎn)換成列表,然后通過join函數(shù)再將其轉(zhuǎn)換成列表,所以空間復(fù)雜度不是O(1)# # 刪除前后空白
# s = s.strip()
# # 反轉(zhuǎn)整個(gè)字符串
# s = s[::-1]
# # 將字符串拆分為單詞,并反轉(zhuǎn)每個(gè)單詞
# s = ' '.join(word[::-1] for word in s.split())
# return s# Solution2# 使用雙指針;
class Solution:def reverseWords(self, s: str) -> str:# 將字符串拆分為單詞,即轉(zhuǎn)換成列表類型words = s.split()# 反轉(zhuǎn)單詞left, right = 0, len(words) - 1while left < right:words[left], words[right] = words[right], words[left]left += 1right -= 1# 將列表轉(zhuǎn)換成字符串return " ".join(words)```