LeetCode_Length of Last Word

Length of Last Word

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.

Example:



1. 字符串处理

本题考查python中基本的字符串处理函数,比较简单。具体实现方法如下:
(其中之所以需要使用 strip() 是因为当字符串为 “a ” 时,最后一个单词应该是 “a”)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
result = 0

words = s.strip().split(' ')

if len(words) == 0:
return 0
else:
return len(words[-1])