leetcode-study

58. Length of Last Word

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        """
        Return the length of the last word in the string s.
        
        Parameters:
            s (str): An input string consisting of English letters and spaces.
        
        Returns:
            int: The length of the last word in s.
        """
        # Initialize index to the last character of the string.
        i = len(s) - 1
        
        # Skip any trailing spaces at the end of the string.
        while i >= 0 and s[i] == ' ':
            i -= 1
        
        # This counter keeps track of the length of the last word.
        length = 0
        
        # Count the number of characters until we hit a space or the start of the string.
        while i >= 0 and s[i] != ' ':
            length += 1
            i -= 1
        
        # Return the computed length of the last word.
        return length

Summary of Techniques and Approaches:

These techniques are widely applicable in problems where you need to process parts of a sequence or string in a memory-efficient and elegant manner, especially when dealing with end-based calculations.