Length of Last Word

easy string two pointers

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.

Input"Hello World "
Output5
Skip 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;
}
Time: O(n) Space: O(1)