관리 메뉴

솜씨좋은장씨

[leetCode] 58. Length of Last Word (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 58. Length of Last Word (Python)

솜씨좋은장씨 2020. 3. 12. 04:56
728x90
반응형

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string.

If the last word does not exist, return 0.

 

Note: A word is defined as a maximal substring consisting of non-space characters only.

 

Example:

Input: "Hello World"
Output: 5

 

Solution

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        words = s.split(' ')
        print(words)
        word = [w for w in words if w != '']
        if len(word) == 0:
            answer = 0
        else:
            word = word[-1]
            answer = len(word)
        return answer

 

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

Comments