code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

058 Length Of Last Word

/**
 * 
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

/* 
 * Given a string s consists of upper/lower-case alphabets and empty space characters
 * ' ', return the length of last word (last word means the last appearing word if
 * we loop from left to right) in the string.
 * 
 * If the last word does not exist, return 0.
 * 
 * Note: A word is defined as a maximal substring consisting of non-space characters 
 * only.
 * 
 * Example:
 * 
 * Input: "Hello World"
 * Output: 5 
*/

function lengthOfLastWord(value) {
  if(!value) return 0;
  return value.trim().split(' ').pop().length
}

test('length Of Last Word', () => {
  expect(lengthOfLastWord('Hello World')).toEqual(5)
  expect(lengthOfLastWord('a ')).toEqual(1)
  expect(lengthOfLastWord('')).toEqual(0)
  expect(lengthOfLastWord(' ')).toEqual(0)
});

Created 2020-04-09T20:42:31+00:00 · Edit