Trim trailing whitespace, then scan from right to left to count characters of the last word until encountering a space or start of string.
class Solution:
def lengthOfLastWord(self, s: str) -> int:
i, length = len(s) - 1, 0
while i >= 0 and s[i] == ' ':
i -= 1
while i >= 0 and s[i] != ' ':
length += 1
i -= 1
return length
class Solution {
public int lengthOfLastWord(String s) {
int i = s.length() - 1, length = 0;
while (i >= 0 && s.charAt(i) == ' ') i--;
while (i >= 0 && s.charAt(i) != ' ') {
length++;
i--;
}
return length;
}
}