58. Length of Last Word
題目 / Problem
中文: 給定一個由單字與空格組成的字串 s,請回傳字串中最後一個單字的長度。一個「單字」是指由非空格字元組成的最長子字串。
English: Given a string s consisting of words and spaces, return the length of the last word in the string. A word is a maximal substring consisting of non-space characters only.
Constraints:
- 1 <= s.length <= 10^4
- s 只包含英文字母與空格 ' ' / s consists of only English letters and spaces.
- 至少會有一個單字 / There will be at least one word in s.
Worked example:
- Input: s = " fly me to the moon "
- Output: 4
- Explanation: 最後一個單字是 "moon",長度為 4 / The last word is "moon" with length 4. 注意末尾還有空格要先跳過 / Note the trailing spaces must be skipped first.
名詞解釋 / Glossary
- 字串 / string:在 C 裡是以
\0結尾的字元陣列 (char *);在 C++ 裡通常用std::string類別。 / In C a string is a\0-terminatedchararray; in C++ we usually use thestd::stringclass. - 索引 / index:陣列中元素的位置編號,從 0 開始。 / The numerical position of an element in an array, starting at 0.
- 從尾端掃描 / scan from the end:從字串最後一個字元開始往前走,而不是從頭開始。對於「找最後一個 X」的問題非常有效率,因為一旦找到就能立即停下。 / Walk the string from the last character backward to the front. Efficient for "find the last X" problems because we can stop as soon as we find it.
- 空格 / whitespace character:這題只會出現 ASCII 半形空格
' '(值為 32)。 / In this problem, only the ASCII space character' '(value 32) appears. strlen:C 標準函式,回傳字串中\0之前的字元數,時間複雜度為 O(n)。 / Standard C function that returns the number of characters before the terminating\0; runs in O(n).size_t:C/C++ 中用來表示「大小或長度」的無號整數型別。 / An unsigned integer type used for sizes and lengths in C/C++.
思路
最直覺的暴力做法是:先用空格把整個字串切成許多單字,存進一個陣列,再取最後一個單字計算長度。這個方法可行,但要額外分配記憶體,而且我們其實只需要「最後一個單字」,把整個字串都切開就太浪費了。更好的方法是從字串的尾端往前掃:先跳過末尾連續的空格(像 "...moon " 結尾有兩個空格),找到最後一個非空格字元的位置;然後再繼續往前走,數出有幾個連續的非空格字元,直到碰到空格或走出字串為止。這個計數就是答案。整個過程只走一遍字串的一部分,不需要額外空間,是最理想的線性時間解。關鍵不變量是:當我們從尾端跳完空格後,當前指到的字元一定屬於最後一個單字;接著只要持續往前走並計數,就能準確得到該單字的長度。
The brute-force idea would be to split the whole string by spaces into a list of words and then take the length of the last one. That works but allocates extra memory just to throw most of it away — we only care about one word. A better approach scans from the end of the string toward the front. First, skip any trailing spaces (e.g., the two spaces at the end of "...moon "); the index now points to the last character of the last word. Then keep moving left, incrementing a counter, until we either fall off the start of the string or hit another space. That counter is the answer. We touch at most O(n) characters once and need no extra memory. The key invariant is: after skipping trailing spaces, the current index is guaranteed to lie inside the last word, so the subsequent count gives exactly its length.
逐步走查 / Walkthrough
Input: s = " fly me to the moon " (length 27, indices 0..26)
| Step | i |
s[i] |
Action / 動作 | length |
|---|---|---|---|---|
| init | 26 | ' ' |
從最後一個索引開始 / start at last index | 0 |
| skip | 26 | ' ' |
是空格,往左 / space, move left | 0 |
| skip | 25 | ' ' |
還是空格,往左 / still space, move left | 0 |
| stop-skip | 24 | 'n' |
非空格,跳出 skip 迴圈 / non-space, exit skip loop | 0 |
| count | 24 | 'n' |
計數 +1,往左 / count, move left | 1 |
| count | 23 | 'o' |
計數 +1,往左 / count, move left | 2 |
| count | 22 | 'o' |
計數 +1,往左 / count, move left | 3 |
| count | 21 | 'm' |
計數 +1,往左 / count, move left | 4 |
| stop-count | 20 | ' ' |
碰到空格,停止 / hit space, stop | 4 |
最終回傳 length = 4 / Return length = 4. ✅
Solution — C
/*
* 演算法 / Algorithm:
* 1. 從字串尾端往前掃,先跳過所有結尾的空格。
* Scan from the end, skipping all trailing spaces first.
* 2. 接著一邊往前走一邊計數,直到碰到空格或走到字串開頭。
* Then count non-space chars walking left until a space or start of string.
*/
#include <string.h> // 引入 strlen / include strlen
int lengthOfLastWord(char* s) {
// strlen 回傳 '