Length of the Last Word in a Sentence
Problem
Given a sentence with words separated by spaces (with possible leading or trailing spaces), return the length of the last word. Walk from the right end: first skip every trailing space, then count letters until the next space or until you fall off the start.
Input
"Hello World "Output
5Skip the two trailing spaces, count W-o-r-l-d.
def 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;
}