###### tags: `Leetcode` `easy` `string` `python` `c++` # 58. Length of Last Word ## [題目來源:] https://leetcode.com/problems/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. ## 解題想法: 1. 直接用split()切 2. 從尾巴找字直到遇到' ' ## Python(Sol1): ``` python= class Solution(object): def lengthOfLastWord(self, s): """ :type s: str :rtype: int """ res=0 tail=len(s)-1 #去尾空格 while tail>=0 and s[tail]==' ': tail-=1 #找最後字 while tail>=0 and s[tail]!=' ': tail-=1 res+=1 return res if __name__ == '__main__': result = Solution() s = " fly me to the moon " ans = result.lengthOfLastWord(s) print(ans) ``` ### Python(Sol2): ``` python= class Solution(object): def lengthOfLastWord(self, s): """ :type s: str :rtype: int """ last=s.strip().split() return len(last[-1]) ``` ## C++: ``` cpp: #include<iostream> using namespace std; class Solution { public: int lengthOfLastWord(string s) { int tail=s.size()-1; int res=0; while (tail>=0 && s[tail]==' '){ tail-=1; } while (tail>=0 && s[tail]!=' '){ tail-=1; res+=1; } return res; } }; int main(){ string s=" fly me to the moon "; Solution res; int ans=res.lengthOfLastWord(s); cout<<ans<<endl; return 0; } ```