Python solution with detailed explanation


  • 0
    G

    Solution

    Length of Last Word https://leetcode.com/problems/length-of-last-word/?tab=Description

    Algorithm

    • Start from the end and skip all empty spaces.
    • Then start moving back till you hit a space or the start of the string.
    class Solution(object):
        def lengthOfLastWord(self, s):
            """
            :type s: str
            :rtype: int
            """
            lidx = len(s)-1
            while lidx > -1 and s[lidx] == " ":
                lidx -= 1
            cnt = 0
            while lidx > -1 and s[lidx] != " ":
                lidx -= 1
                cnt += 1
            return cnt
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.