개발조각

[리트코드] 58. Length of Last Word 본문

알고리즘🅰/리트코드

[리트코드] 58. Length of Last Word

개발조각 2022. 11. 5. 12:52
728x90
반응형

문제

 

https://leetcode.com/problems/length-of-last-word/submissions/

 

Length of Last Word - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

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


풀이

Example 2:

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

이러한 예제가 주어지면 

 

1. s를 공백 기준으로 자른다.

2. 마지막부터시작해서 문자열이 있으면 길이를 반환해준다.


소스코드

var lengthOfLastWord = function(s) {
    let strs = s.split(' ');
    console.log(strs);
    
    let i = strs.length-1;
    while(true){
        if(strs[i]){
            return strs[i].length;
            break;
        }else i--;
    }
};


알고리즘 순서도

728x90
반응형
Comments