← switch

58. Length of Last Word

easy

String

read the problem on leetcode →

first solved 15 Aug 2024 · 2 accepted submissions

python
class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        # lststr=s.split()
        # return len(lststr[-1])
        i = len(s) - 1

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

        length = 0

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

        return length



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