Solution to Length of Last Word by LeetCode
Question: https://oj.leetcode.com/problems/length-of-last-word/ Question Name: Length of Last Word
1 2 3 4 5 6 7 8 9 10 | class Solution: # @param s, a string # @return an integer def lengthOfLastWord(self, s): s = s.strip() # Remove the spaces at the beginning and end length = 0 for letter in s: if letter == " ": length = 0 # Waiting for the next word else: length += 1 # Inside one word return length |
If strip() method is forbidden or unusable, we could do it like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class Solution: # @param s, a string # @return an integer def lengthOfLastWord(self, s): preLength = 0 # Length of previous word length = 0 # Length of current word for letter in s: if letter == " ": # Waiting for the next word if length != 0: # This is a single zero or # leading one in zeros preLength = length length = 0 else: # A following zero in zeros pass else: # Inside one word length += 1 if length == 0: return preLength # s ends with zero(s) else: return length # s ends with word |