題目

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.

Example 1

1
2
3
Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.

Example 2

1
2
3
Input: s = "   fly me   to   the moon  "
Output: 4
Explanation: The last word is "moon" with length 4.

Example 3

1
2
3
Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.

Constraints:

  • 1 <= s.length <= 104
  • s consists of only English letters and spaces ‘ ‘.
  • There will be at least one word in s.

解釋題目

給你一個只包含英文字母和空格的字串 s,請你回傳「最後一個單字」的長度。
這裡的「單字」定義為:一段由非空格字元組成、且被空格分隔的最大子字串。
注意事項:

  • 字串 s 可能前後有空格,也可能單字之間有多個空格。
  • 一定至少有一個單字存在。

簡單來說,就是要你找出最後一個單字(不管前面有多少空格或單字),然後回傳它的字母數量。

思路 (1)

  1. 由左至右正向的操作,遍歷所有字母,計算所有單字的長度。
  2. 計算到最後一個單字會覆蓋前面的紀錄

程式碼 (1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
def lengthOfLastWord(self, s: str) -> int:
length = 0
counting = False
for i in s:
# 要是空格
if i != ' ':
# 還沒開始算
if not counting:
counting = True
length = 0
# 開始計算單字長度
else:
length += 1
else:
counting = False
return length

思路 (2)

  1. 由右至左反向遍歷,記住最後一個單字的最後一個字母的 index
  2. 開使計算單字長度,直到再次碰到空格
  3. last index 可以由 len(s) 求出

程式碼 (2)

1
2
3
4
5
6
7
8
9
10
11
class Solution:
def lengthOfLastWord(self, s: str) -> int:
end = len(s) - 1
while end >= 0 and s[end] == " ":
end -= 1

length = 0
while end >= 0 and s[end] != " ":
length += 1
end -= 1
return length