Length of Last Word

신병규·2022년 9월 20일
0

Algorithm

목록 보기
2/6

단어와 공백으로 구성된 문자열이 주어지면 문자열의 마지막 단어 길이를 반환합니다.

단어는 공백이 아닌 문자로만 구성된 문자열입니다.

Example 1:

Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.

Example 2:

Input: s = "   fly me   to   the moon  "
Output: 4
Explanation: The last word is "moon" with length 4.

Example 3:

Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.
/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLastWord = function (s) {
  let arr = s.split(' ')

  if (arr[arr.length - 1] === '') {
    let newArr = arr.filter((el) => el.length > 0)
    return newArr[newArr.length - 1].length
  }
  return arr[arr.length - 1].length
};

console.log(lengthOfLastWord("Hello World"))
console.log(lengthOfLastWord("   fly me   to   the moon  "))
console.log(lengthOfLastWord("luffy is still joyboy"))

split(’ ‘)로 띄어쓰기 기준으로 배열로 만들어 마지막요소의 길이 리턴 ,
만약 마지막이 단어가 아닐경우 filter로 걸러서 마지막요소 길이 리턴

최다추천코드

return s.trim().split(" ").pop().length;

*** trim 학습필요

0개의 댓글