--- tags: LeetCode --- # 58. Length of Last Word Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string. If the last word does not exist, return 0. Note: A word is defined as a maximal substring consisting of non-space characters only. Example: >Input: "Hello World" Output: 5 輸入範本如下 ```C# public class Solution { public int LengthOfLastWord(string s) { } } ``` 自行限制 1. 不准使用 Trim() 2. 不准使用 Substring() & LastIndexOf() ```C# public int LengthOfLastWord(string s) { var input = s.Trim(); // 防止機巴測資 , e.g. "E " return input.Substring(input.LastIndexOf(' ') + 1).Length; } ``` 3. 不准使用 Split() ``` public int LengthOfLastWord(string s) { var input = s.Trim().Split(' '); return input.Length == 0 ? 0 : input[input.Length - 1].Length; } ``` ### 直覺想法 我應該怎麼取出最後一個句子!? , 第一個想到的其實是使用 Split , 然後才想到可以用 LastIndexOf 去取出最後一個 ' ' 的位置再加一即是最後一個句子在整個字串的索引位置. 不過仔細想想 , 其實倒著走訪字串 , 只要碰到第一個 ' ' , 該 ' ' 的右邊其實就是最後一個句子了. Runtime: 72 ms, faster than 89.68% of C# online submissions for Length of Last Word. Memory Usage: 22.1 MB, less than 7.14% of C# online submissions for Length of Last Word. ```C# public int LengthOfLastWord(string s) { int ans = 0; var index = s.Length - 1; // 先過濾掉尾部的空白字元. 等同於 TrimEnd() while (index >= 0 && char.IsWhiteSpace(s[index])) { index--; } for (; index >= 0; index--) { if (!char.IsWhiteSpace(s[index])) { ans++; } else { return ans; } } return ans; } ``` ### Thank you! You can find me on - [GitHub](https://github.com/s0920832252) - [Facebook](https://www.facebook.com/fourtune.chen) 若有謬誤 , 煩請告知 , 新手發帖請多包涵 # :100: :muscle: :tada: :sheep: