反轉所有的單字 Reverse Words in a String_Leetcode 精選75題解析

2024/02/29閱讀時間約 3 分鐘

題目敘述

題目會給我們一個字串s作為輸入,要求我們以white space空白為切割符號,切割出每個單字,並且反轉其順序後,以字串形式最為最後的輸出。

題目的原文敘述


測試範例

Example 1:

Input: s = "the sky is blue"
Output: "blue is sky the"
Example 2:

Input: s = " hello world "
Output: "world hello"
Explanation: Your reversed string should not contain leading or trailing spaces.
Example 3:

Input: s = "a good example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

約束條件

Constraints:

  • 1 <= s.length <= 10^4

字串s的長度介於1~10^4之間

  • s contains English letters (upper-case and lower-case), digits, and spaces ' '.

字串s只會包含(大寫、小寫)英文字母,數字,和空白

  • There is at least one word in s.

字串s裡面至少包含一個單字。


演算法

這題的考點主要在於字串操作的熟悉度。

有不種一只解法。

這邊我們採用內建的字串函數與python slicing 切片語法,作為示範。

首先用s.split(),用空白字元切割出每一個單字。

接下來,用[::-1]反轉單字的出現順序。

最後,用" ".join合併每個單字,倆倆單字中間用一個空白作為間隔,最後以字串的形式輸出答案。


程式碼

class Solution:
def reverseWords(self, s: str) -> str:

# Parse each token by whitespace, and reverse order
tokens = s.split()[::-1]

# Combine with each token, separated by one whitespace
return " ".join( tokens )

額外補充,Python 官方文件關於 str.split() 函式的介紹,在切割有規律的字串時,很實用的內建function。


以行動支持創作者!付費即可解鎖
本篇內容共 1386 字、0 則留言,僅發佈於Leetcode 精選75題 上機考面試題 詳解你目前無法檢視以下內容,可能因為尚未登入,或沒有該房間的查看權限。
45會員
288內容數
由有業界實戰經驗的演算法工程師, 手把手教你建立解題的框架, 一步步寫出高效、清晰易懂的解題答案。 著重在讓讀者啟發思考、理解演算法,熟悉常見的演算法模板。 深入淺出地介紹題目背後所使用的演算法意義,融會貫通演算法與資料結構的應用。 在幾個經典的題目融入一道題目的多種解法,或者同一招解不同的題目,擴展廣度,並加深印象。
留言0
查看全部
發表第一個留言支持創作者!