Leetcode 58. Length of Last Word == ### Description (easy) 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: 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. #### Constraints: - 1 <= s.length <= 104 - s consists of only English letters and spaces ' '. - There will be at least one word in s. ### 想法 c : 直接用for loop倒著找,從串列的最後面開始尋找,若是最後面是space就跳過他 python : len()取得長度,strip()效果會切掉頭尾空白,使用split('')可以切斷字串[hello world]會變成['hello', 'world'] 然後-1取倒數第一個物件 ### 程式碼 #### c: ```c= int lengthOfLastWord(char * s){ int count=0; for (int i = strlen(s)-1; i >=0; i--) { if(s[i]!=' ') count++; else if(s[i]==' '&& count!=0) break; } return count; } ``` Runtime: 2 ms Memory Usage: 5.7 MB #### python: ```python= class Solution: def lengthOfLastWord(self, s: str) -> int: return len(s.strip().split(' ')[-1]) ``` Runtime: 48 ms Memory Usage: 13.8 MB