본문 바로가기
LeetCode

[LeetCode] 58. Length of Last Word

by JungSeung 2023. 12. 28.
728x90

https://leetcode.com/

Given a string s consisting of words and 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 <= 10^4
  • s consists of only English letters and spaces ' '.
  • There will be at least one word in s.

 

Code :

var lengthOfLastWord = function(s) {
    // 단어의 길이를 저장할 변수
    let length = 0;
    // 문자열 끝에서부터 시작하여 공백을 건너뛰기
    let end = s.length - 1;
    // 문자열 끝에서부터 시작하여 마지막 공백을 건너뛰기
    while (end >= 0 && s[end] === ' ') {
        end--;
    }
    // 공백 다음부터 시작하여 마지막 단어의 길이 계산
    while (end >= 0 && s[end] !== ' ') {
        length++;
        end--;
    }
    // 최종 결과 반환
    return length;
};

 

Solutions Code :

/*
이 문제를 해결하기 위해 trim() 메서드를 사용할 수 있습니다.

trim() 메서드는 문자열의 양쪽 끝에서 공백을 제거하고 원래 문자열을 수정하지 않고 새로운 문자열을 반환합니다.

이후에는 마지막 단어의 앞에 있는 공백(마지막 공백)의 인덱스를 찾아 이 인덱스를 문자열의 전체 길이에서 빼주면 됩니다. ("-1"을 고려한 값)
*/
var lengthOfLastWord = function(s) {
    // 문자열 양 끝의 공백을 제거한 새로운 문자열 생성
    let trimmedString = s.trim();
    
    // 최종 결과 반환: 전체 길이에서 마지막 공백의 위치를 뺀 값
    return trimmedString.length - trimmedString.lastIndexOf(' ') - 1;
};

 

 

출처 : https://leetcode.com/problemset/all/

 

Problems - LeetCode

Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

leetcode.com

 

728x90

'LeetCode' 카테고리의 다른 글

[LeetCode] 60. Permutation Sequence  (0) 2023.12.29
[LeetCode] 59. Spiral Matrix II  (0) 2023.12.29
[LeetCode] 57. Insert Interval  (0) 2023.12.27
[LeetCode] 56. Merge Intervals  (0) 2023.12.27
[LeetCode] 55. Jump Game  (2) 2023.12.26