복's

[ LeetCode - 58 ] Length of Last Word 본문

알고리즘/LeetCode

[ LeetCode - 58 ] Length of Last Word

나복이 2023. 11. 2. 14:26
728x90

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

 

Length of Last Word - LeetCode

Can you solve this real interview question? Length of Last Word - 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:

leetcode.com

문자열 기본 문제로 크게 고민하지 않았다.

하지만 java 문자열 구하는 법에 대해서 30초동안 생각한 나에게 알맞는 문제 ㅎ..


[ 📌 풀이 ]

1) 앞 뒤로 공백 제거

2) 문자 사이 공백을 기준으로 문자열 split

3) 배열의 마지막 요소의 길이를 return


[ 📌 코드 - Python ]

"""
# Author    : Lee In Bok 
# Date      : 2023.11.02(Thu)
# Spend Time: 02m 04s
# Runtime   : 40 ms (Beats 42.79%)
# Memory    : 16.3 MB (Beats 61.42%)
# Algoritm  : Array
"""

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        return len(s.strip().split(" ")[-1])

s = Solution()
result = s.lengthOfLastWord("   fly me   to   the moon  ")

print(result)

[ 📌 코드 - Java ]

위 코드는 1ms 나오고, 밑에 코드가 0ms 나오는 코드다.

역시 직접 하나 하나 비교하고 구하는게 시간이 적게 나오네

/**
* Author    : Lee In Bok 
* Date      : 2023.11.02(Thu)
* Spend Time: 02m 04s
* Runtime   : 0 ms (Beats 100%)
* Memory    : 40.4 MB (Beats 78.81%)
* Algoritm  : String
 */

public class Q58_LengthOfLastWord {
    public static void main(String[] args) {
        Solution s = new Solution();

        int result = s.lengthOfLastWord("a");
        System.out.println(result);
    }
}

class Solution {
    public int lengthOfLastWord(String s) {
        String[] arr = s.strip().split(" ");

        return arr[arr.length - 1].length();
    }
}

[ 📌 다른 사람 코드 - Java ]

class Solution {
    public int lengthOfLastWord(String s) {
        int cnt = 0;

        for(int i = s.length() - 1; i >= 0; i--){
            if(s.charAt(i) != ' '){
                cnt++;
            } else {
                if(cnt > 0){
                    return cnt;
                }
            }
        }

        return cnt;
    }
}

[ 📌 결과 - Python ]

[ Result - Python ]

[ 📌 결과 - Java ]

[ Result - Java ]

728x90