[LeetCode/Python] 58. Length of Last Word

2025. 3. 28. 01:38·Algorithm/LeetCode

다시 알고리즘 공부를 꾸준히 하기 위한 작심삼일 x 1년! 프로젝트를 시작했다. (작심삼일이라도 꾸준히 하자라는 마음가짐이다)

 

문제 링크:

https://leetcode.com/problems/length-of-last-word/description/?envType=study-plan-v2&envId=top-interview-150

 

Easy 난이도인 만큼, 특히 python으로서는 아주 풀기 쉬운 문제였다.

 

[내 풀이]

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

 

시간 복잡도

where n is the length of the input string

Stripping: O(n)

Splitting: O(n)

=> O(n)

 

 

[다른 풀이]

1.

strip()을 할 필요가 없다. 어차피 split() 하면서 whitespace는 자동으로 strip 되기 때문이다.

참고로 split() 함수의 default 구분자는 공백 문자다(space, tab, enter 등)

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        word_list = s.split()
        if word_list:
	        return len(word_list[-1])
        return 0

 

또한, 조건에서 s의 길이는 1 이상이라고는 했으나, ' ' 로만 이루어졌을 수도 있기 때문에 그런 경우를 위해 if문으로 word_list가 존재하는지 확인하는 조건문을 넣은 것 같다.

그러나, 그 밑에 조건에 [There will be at least one word in s] 라고 되어 있었기 때문에 사실상 조건문은 필요가 없긴 하다!

 

2.

빠른 코드로 솔루션에 소개되어 있는 코드다. 위의 코드는 가장 쉬운 코드이지만, 시간복잡도가 O(n)이므로 사실 시간효율적이진 않기 떄문이다.

class Solution(object):
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        i = len(s) - 1 
        length = 0

        while i >= 0 and s[i] == " ":
            i -= 1

        while i >= 0 and s[i] != " ":
            length += 1
            i -= 1

        return length

직접 마지막 단어를 추출해내는 코드다. 문장의 맨 뒤에서 시작해서 white space인 글자는 건너띄게 하고,

english letter일 경우에만 length에 추가하는 코드다.

 

모든 문장을 trim하거나 split할 필요가 없어 당연히 1번의 코드보다 시간이 더 빠를 것이다!!! WOW!

음.. Easy문제는 빠르게 풀었을 경우, 더 효율적인 다른 코드가 있는지 생각해보는 시간을 가져야겠다.

'Algorithm > LeetCode' 카테고리의 다른 글

[LeetCode/Python] 125. Valid Palindrome  (0) 2025.04.01
[LeetCode/Python] 9. Palindrome Number  (0) 2024.09.17
[LeetCode/Python] 67. Add Binary  (0) 2024.09.16
[LeetCode/Python] 13. Roman to Integer  (0) 2024.08.12
[LeetCode/Python] 1492. The kth Factor of n  (0) 2024.07.23
'Algorithm/LeetCode' 카테고리의 다른 글
  • [LeetCode/Python] 125. Valid Palindrome
  • [LeetCode/Python] 9. Palindrome Number
  • [LeetCode/Python] 67. Add Binary
  • [LeetCode/Python] 13. Roman to Integer
빵빵0
빵빵0
(아직은) 공부하고 정리하는 블로그입니다.
  • 빵빵0
    Hack Your World
    빵빵0
  • 전체
    오늘
    어제
    • 분류 전체보기 (92)
      • Error Handling (7)
      • Project (5)
        • MEV (2)
      • Architecture (0)
        • API (0)
        • Cache (0)
        • 사소한 고민거리 (0)
      • Computer Science (4)
        • Data Structure (2)
        • Database (1)
        • Cloud (0)
        • OS (0)
        • Infra, Network (1)
        • AI (0)
      • Language (8)
        • Go (8)
        • Rust (0)
        • Python (0)
        • Java (0)
      • Algorithm (40)
        • BaekJoon (18)
        • Programmers (7)
        • LeetCode (6)
        • NeetCode (9)
      • SW Books (9)
        • gRPC Up & Running (1)
        • System Design Interview (2)
        • 스프링 입문을 위한 자바 객체지향의 원리와 이해 (6)
        • 블록체인 해설서 (0)
        • 후니의 쉽게 쓴 CISCO 네트워킹 (0)
      • BlockChain (4)
        • Issues (0)
        • Research (4)
        • Tech (0)
      • Own (8)
        • TIR(Today I Read) (3)
        • Personal (2)
        • Novel (0)
        • Memo (3)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    go
    KBW
    스택
    golang
    BEAKJOON
    블록체인
    큐
    프로그래머스
    Palindrome
    Programmers
    context
    MongoDB
    ethereum
    DP
    백준
    BFS
    MEV
    BaekJoon
    Python
    Greedy
    EVM
    blockchain
    goroutine
    candlechart
    LeetCode
    2024
    NeetCode
    Hash Table
    chart
    two pointer
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
빵빵0
[LeetCode/Python] 58. Length of Last Word
상단으로

티스토리툴바