LeetCode - 58. Length of Last Word

henu·2023년 8월 24일
0

LeetCode

목록 보기
14/186
post-thumbnail

Problem

단어와 공백으로 이루어진 문자열 s가 주어질때, 마지막 단어의 길이를 리턴하라.
여기서 단어란 공백이 아닌 글자로만 이루어진 가장 긴 부분 문자열이다.

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.

Solution

var lengthOfLastWord = function(s) {
    return s.trimEnd().length - s.trimEnd().lastIndexOf(' ') - 1;
};

Explanation

처음에는 단순히 s 자체에 lastIndexOf 메소드를 사용해서 마지막 공백의 인덱스를 추출했는데 그럴 경우 예시2와 같이 끝의 공백이 있는 경우가 해결되지 않았다.
그래서 trimEnd 메소드를 사용해서 끝의 공백을 제거하고 해결하였다.

0개의 댓글

관련 채용 정보