LeetCode: Length of Last Word
Question
Given a string s consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0.
A word is a maximal substring consisting of non-space characters only.
Solution#1
def length_of_last_word(s)
last_word = s.split(" ")
last_word.empty? ? 0 : last_word.last.length
end
Solution#2
def length_of_last_word(s)
if s.split(' ').length == 0
return 0
else
s.split(' ').last.length
end
end
Comments