58. Length of Last Word 發表於 2023-02-13 | 分類於 leetcode prolemsolutionoption 112345678910111213class Solution {public: int lengthOfLastWord(string s) { int l =-1 , r = s.size()-1; while(r >l && s[r]==' ') r--; for(int i=0;i<=r; ++i){ if(s[i] ==' ') l = i; } if(l==-1) return r+1; return r-l; }}; option 2123456789101112class Solution {public: int lengthOfLastWord(string s) { int r= s.size()-1; while(r>-1 && s[r]==' ') r--; if(r==-1) return 0; for(int i=r;i>-1;i--){ if(s[i] == ' ') return r-i; } return r+1; }}; analysis time complexity O(n) space complexity O(1)