Length of Last Word | LeetCode 58

[Written explanation will be added soon]

AFFILIATE LINKS

Great resource I use to learn algorithms.
40% off Tech Interview Pro: http://techinterviewpro.com/terriblewhiteboard
20% off CoderPro: http://coderpro.com/terriblewhiteboard


Here is the full implementation.

/**
 * @param {string} s
 * @return {number}
 */
let lengthOfLastWord = function(s) {
  let lastWordLength = 0;
  let beforeFirstNonEmptyChar = true;

  if (s.length === 0) {
    return lastWordLength;
  }

  for (let i = s.length - 1; i >= 0; i--) {
    if (s.charAt(i) !== ' ') {
      lastWordLength++;
      beforeFirstNonEmptyChar = false;
    } else if (!beforeFirstNonEmptyChar) {
      break;   
    }
  }

  return lastWordLength;
};