본문 바로가기

카테고리 없음

[LeetCode] 58. Length of Last Word

반응형

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

 

Length of Last Word - LeetCode

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: s = "Hello World" Output: 5 Explanation: Th

leetcode.com

 

string에서 last word의 길이를 구하는 문제

space 처리를 하는 문제로 매우 쉽다.

 

python solution 1.

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        return len(s.rstrip(' ').rsplit(' ', 1)[-1])

python one line으로 해결ㅋㅋㅋㅋ

이렇게 작성하면 분명 어이없어 하겠지ㅋㅋㅋ
그래도 나름 함수도 최소한의 연산만 하도록 사용했다.

 

python solution 2.

class Solution:
    def lengthOfLastWord(self, s: str) -> int:

        i = len(s) - 1
        result = 0

        while s[i] == ' ':
            i -= 1
        while i >= 0 and s[i] != ' ':
            result += 1
            i -= 1

        return result

아마 이게 제일 무난한 답변이 아닐까 싶다.

그런데 루프 한 개로도 구현이 가능하다는 이야기 발견! 참을수 없지...

 

python solution 3.

class Solution:
    def lengthOfLastWord(self, s: str) -> int:

        i = len(s) - 1
        result = 0

        while i >= 0:
            if s[i] != ' ':
                result += 1 
            elif result > 0:
                return result
            i -= 1

        return result

루프 한 개로 변경

인터뷰에서 누가 혹시 물어보면 이렇게 작성 할 수도 있지만

읽기 좋은 코드는 아니라서 이렇게 쓰지는 않을 듯

반응형