Length of Last Word
Problem
Given a string s consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0. A word is a maximal substring consisting of non-space characters only.
"Hello World "5def length_of_last_word(s):
i = len(s) - 1
while i >= 0 and s[i] == ' ':
i -= 1
length = 0
while i >= 0 and s[i] != ' ':
length += 1
i -= 1
return length
function lengthOfLastWord(s) {
let i = s.length - 1;
while (i >= 0 && s[i] === ' ') i--;
let len = 0;
while (i >= 0 && s[i] !== ' ') { len++; i--; }
return len;
}
class Solution {
public int lengthOfLastWord(String s) {
int i = s.length() - 1;
while (i >= 0 && s.charAt(i) == ' ') i--;
int len = 0;
while (i >= 0 && s.charAt(i) != ' ') { len++; i--; }
return len;
}
}
int lengthOfLastWord(string s) {
int i = (int)s.size() - 1;
while (i >= 0 && s[i] == ' ') i--;
int len = 0;
while (i >= 0 && s[i] != ' ') { len++; i--; }
return len;
}
Explanation
To measure the last word, we do not need to split the whole sentence — we just start at the right end and work backwards. There are only two small steps: skip any trailing spaces, then count letters until the next space.
We set i to the last index. The first while loop moves i left past every trailing ' '. The second loop then counts: as long as i is in range and s[i] is not a space, we add one to length and step left. When we hit a space or run off the start, length holds the answer.
This works because the last word is the run of non-space characters sitting just before any trailing spaces, and scanning right-to-left lands on it first.
Example: "Hello World ". We skip the two trailing spaces, then count d, l, r, o, W — five letters — and stop at the space before World, returning 5.
We pass over each relevant character at most once, so the work is linear in the length of the string and uses only a couple of variables.