Difficulty : Easy
Approach 1 : use rstrip to treat with case with rightside spaces.
class Solution:
def lengthOfLastWord(self, s: str) -> int:
count = 0
s = s.rstrip()
for i in range(len(s) - 1, -1, -1):
if s[i] == " ":
break
count += 1
return count
Approach 2 : no rstrip, put another if when the letter we encountered is space to check it's rightside space or not. too slow :(
class Solution:
def lengthOfLastWord(self, s: str) -> int:
count = 0
have_to_break = False
for i in range(len(s) - 1, -1, -1):
if s[i] == " ":
if have_to_break:
break
else:
have_to_break = True
count += 1
return count