42ns simple Python solution with no extra built-in functions, O(n) time, and O(1) space


  • 0
    P
        len_s = len(s)
        
        if len_s == 0:
            return 0
    
        idx = len_s-1       
        counter = 0         # count how many chars in the last word
        
        # Get to the last char of the last word
        while s[idx] == " " and idx > 0:
            idx -= 1
        
        # Now start couting
        while s[idx] != " " and idx >= 0:
            counter += 1
            idx -= 1
        
        return counter

Log in to reply
 

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