코드노트

LeetCode 58. Length of Last Word 문제풀이 자바스크립트 본문

Code note/자바스크립트 알고리즘 문제풀이

LeetCode 58. Length of Last Word 문제풀이 자바스크립트

코드노트 2022. 9. 21. 16:19

문제 설명

더보기

Given a string s consisting of words and spaces, return the length of the last word in the string.

word is a maximal substring consisting of non-space characters only.

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

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

 

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

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

 

- 이번 문제는 배열에 있는 문자들 중에서 마지막 문자열을 반환하면 되는 문제였다.

- 간단한 문제라고 생각했고 split을 통해서 문자열을 " "빈공간으로 배열들을 만들어 마지막 문자열을 반환했었다.

2번째 예제에서 실패했다.

- 끝 부분에 " " 빈배열이 있었다.

그래서 for of를 통해서 split으로 나눈 문자들의 길이를 비교하여 1개 이상의 문자들을 재 배열하고 마지막 문자의 길이를 반환하였다.

 

var lengthOfLastWord = function (s) {
  let str = s.split(" ");
  let last_str = [];
  for (let i of str) {
    if (i.length > 0) {
      last_str.push(i);
    }
  }
  last_str = last_str.pop();
  return last_str.length;
};

 

 

더 간단한 예제..

var lengthOfLastWord = function(s) {
    return s.trim().split(" ").pop().length;
};

- trim으로 양끝의 공백을 제거하면 되는거였는데.. 생각만하고 활용을 못했당...

- 이 한줄이면 되는것을..