58. Length of Last Word ¶ Time: $O(n)$ Space: $O(1)$ C++JavaPython 1 2 3 4 5 6 7 8 9 10 11 12 13 14class Solution { public: int lengthOfLastWord(string s) { int i = s.length() - 1; while (i >= 0 && s[i] == ' ') --i; const int lastIndex = i; while (i >= 0 && s[i] != ' ') --i; return lastIndex - i; } }; 1 2 3 4 5 6 7 8 9 10 11 12 13class Solution { public int lengthOfLastWord(String s) { int i = s.length() - 1; while (i >= 0 && s.charAt(i) == ' ') --i; final int lastIndex = i; while (i >= 0 && s.charAt(i) != ' ') --i; return lastIndex - i; } } 1 2 3 4 5 6 7 8 9 10 11class Solution: def lengthOfLastWord(self, s: str) -> int: i = len(s) - 1 while i >= 0 and s[i] == ' ': i -= 1 lastIndex = i while i >= 0 and s[i] != ' ': i -= 1 return lastIndex - i