Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.

For example,
Given s = "Hello World",
return 5.

思路

想办法提取这个字符串所有的单词,然后就可以得到最后一个单词了。关键就是在于空格的处理与分割。需要注意多个空格、开头为空格的情况。

在这里利用了python内置的split方法,也是可行的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
if (len(s)):
l = s.split()
if (len(l)):
return len(l[len(l)-1])
else:
return 0
else:
return 0

P.S. 290题(Word Pattern)涉及到关于空格处理与分割的方法。