↓快轉到主要內容
  1. LeetCode/

LeetCode 58: Length of Last Word

·1 分鐘· ·
LeetCode Easy String
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2022-05-11

  • 提交紀錄:Accepted ×3 → Wrong Answer → Accepted ×3 → Runtime Error → Accepted ×3

解題思路
#

s.split() 會去掉頭尾空白、把連續空白當成一個分隔,最後一個元素就是最後一個單字(String 模板六)。不想切整個字串的話,可以從尾巴往前:先跳過空白,再數非空白字元。

我的嘗試
#

2022-05 有一版用了 split(" ")[-1],結尾有空白時最後一個元素是空字串:"a " 回傳 0,答案 1。2022-08 重寫時把 [-1] 寫進了 split(-1) 的參數裡(TypeError)。

正確解法
#

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        i = len(s) - 1
        while s[i] == " ":
            i -= 1
        n = 0
        while i >= 0 and s[i] != " ":
            n += 1
            i -= 1
        return n

複雜度
#

時間 O(n),空間 O(1)。

要特別避免的錯誤
#

  • 字串可能以空白結尾,split(" ")[-1] 會拿到空字串。

面試口說整理
#

我從字串尾巴往前,先跳過結尾的空白,再數連續的非空白字元,就是最後一個單字的長度,空間 O(1);用 split() 取最後一個也可以。

相關文章

LeetCode 28: Find the Index of the First Occurrence in a String
·1 分鐘
LeetCode Easy Two-Pointers String String-Matching Z-Algorithm
LeetCode 28 解題筆記:在每個起點比對 needle,或直接用 str.find;index 找不到會丟例外
LeetCode 67: Add Binary
·1 分鐘
LeetCode Easy Math String Bit-Manipulation Simulation
LeetCode 67 解題筆記:從兩個字串的尾巴往前逐位相加,進位是 sum // 2,這一位是 sum % 2
LeetCode 14: Longest Common Prefix
·1 分鐘
LeetCode Easy Array String Trie
LeetCode 14 解題筆記:用最短的字串當上限,逐個位置檢查所有字串是否相同,第一個不同的位置就是答案的長度
LeetCode 13: Roman to Integer
·1 分鐘
LeetCode Easy Hash-Table Math String
LeetCode 13 解題筆記:從左到右加每個符號的值,如果它比右邊的符號小就改成減
LeetCode 27: Remove Element
·1 分鐘
LeetCode Easy Array Two-Pointers
LeetCode 27 解題筆記:寫入指標只寫不等於 val 的數,最後回傳寫入的個數
LeetCode 35: Search Insert Position
·1 分鐘
LeetCode Easy Array Binary-Search
LeetCode 35 解題筆記:找第一個 >= target 的位置(lower bound);半開區間 [l, r) 要配 r = mid,不能寫 r = mid - 1