leetcode-58-length-of-last-word
題目
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 | Input: s = "Hello World" |
Example 2
1 | Input: s = " fly me to the moon " |
Example 3
1 | Input: s = "luffy is still joyboy" |
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)
1 | class Solution: |
思路 (2)
- 由右至左反向遍歷,記住最後一個單字的最後一個字母的 index
- 開使計算單字長度,直到再次碰到空格
- last index 可以由
len(s)
求出
程式碼 (2)
1 | class Solution: |
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 雜耍特技師!