Question:

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.

Example:

  1. Input: "Hello World"
  2. Output: 5

Solution:

  1. /**
  2. * @param {string} s
  3. * @return {number}
  4. */
  5. var lengthOfLastWord = function(s) {
  6. if(!s) return 0;
  7. const arr = s.split(" ");
  8. let i = arr.length;
  9. while(!arr[i] && i > 0 ){
  10. i--;
  11. }
  12. return !arr[i] ? 0 : arr[i].length;
  13. };