Length of Last Word

Jamie·2022년 2월 26일
0

LeetCode

목록 보기
5/18
post-thumbnail

문제

Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string.

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

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.

Constraints:

1 <= s.length <= 104
s consists of only English letters and spaces ' '.
There will be at least one word in s.

풀이

var lengthOfLastWord = function (s) {
    // letter 라는 단어들을 담아줄 새 배열을 선언한다
    // 하나의 단어를 넣어줄 word 문자열을 선언한다
    // s를 반복문을 돌면서 공백이면 넘긴다
    // 공백이 아닐 경우 다음 공백이 나올때까지 word 문자열에 더해주고 공백이 나오면 letter 배열에 push한다
    // 반복문의 끝자리가 문자열일 경우 word의 길이를 리턴한다
    // 반복문의 끝자리가 공백일 경우 letter 맨 마지막 단어의 길이를 리턴한다

    let letter = [];
    let word = "";
    for (let i = 0; i < s.length; i++) {
        if (s[i] === " " && word.length === 0) {
            continue;
        } else if (s[i] === " " && word.length !== 0) {
            letter.push(word);
            word = "";
            continue;
        } else if (i === s.length - 1 && s[i] !== " ") {
            word = word + s[i];
            return word.length;
        } else if (s[i] !== " ") {
            word = word + s[i];
        }
    }
    return letter[letter.length - 1].length;
};

✅ 단어를 넣는 배열과 단어로 모으는 문자열을 선언하고 예외적인 조건에 맞추어 코드를 작성했다.
뭔가 하나하나 복잡하게 코드를 작성한 것 같아서 조금 더 간략하게 짤 수 있는 코드가 있는지 연구를 해봐야 할 것 같다.

profile
공부하고 비행하다 개발하며 여행하는 frontend engineer

0개의 댓글