題目描述
輸入一個英文句子,翻轉句子中單詞的順序,但單詞內字符的順序不變。爲簡單起見,標點符號和普通字母一樣處理。例如輸入字符串"I am a student. “,則輸出"student. a am I”。
思路
代碼
class Solution:
def reverseWords(self, s:str) -> str:
s = s.strip() #去除首尾空格
i = j = len(s) - 1
res = []
while i >= 0:
while i >= 0 and s[i] != " ":
i -= 1
res.append(s[i+1:j+1])
while s[i] == " ":
i -= 1
j = i
return " ".join(res)
複雜度
時間複雜度 O(N): 其中 N 爲字符串 s 的長度,線性遍歷字符串。
空間複雜度 O(N)O(N) : 新建的 list(Python) 中的字符串總長度 ≤N ,佔用 O(N)大小的額外空間。