# 58. Length of Last Word ## 題目概要 給定一個字串,輸出最後一個單字的長度。 ``` Example 1: Input: s = "Hello World" Output: 5 Explanation: The last word is "World" with length 5. Example 2: Input: s = " fly me to the moon " Output: 4 Explanation: The last word is "moon" with length 4. Example 3: Input: s = "luffy is still joyboy" Output: 6 Explanation: The last word is "joyboy" with length 6. ``` ## 解題技巧 - 如果用 split 分隔字串,最後一個元素可能會是空字串而不是單字,所以要先將空字串篩掉再輸出。 ## 程式碼 ```javascript= /** * @param {string} s * @return {number} */ var lengthOfLastWord = function(s) { const arr = s.split(" ").filter(item => item); return arr[arr.length - 1].length; }; ``` ![](https://i.imgur.com/4N6rdrQ.png)