# 58 - Length of Last Word
解法一 - 取出 lastWord,算長度
一開始的直覺做法如下:
但是會掛在這個 case:
"a " or "b a ": 我的輸出是 0,但應該要輸出 1。這是因為我的實作會被最後面的空白騙到。
一個繞開的方法就是先把最後面的空白都移除掉:
效率如下: Runtime: 0 ms, faster than 100.00% of C++ online submissions for Length of Last Word. Memory Usage: 9.5 MB, less than 5.00% of C++ online submissions for Length of Last Word.
解法二 - 從字串尾端開始往前找,找到第一個非 space 的 char 就開始數長度,直到數到 space
實作如下:
效率差不多:
Runtime: 4 ms, faster than 85.62% of C++ online submissions for Length of Last Word. Memory Usage: 8.8 MB, less than 40.76% of C++ online submissions for Length of Last Word.
Last updated