You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
'''
给定一个仅包含大小写字母和空格 ' ' 的字符串 s, 返回其最后一个单词的长度。
如果字符串从左向右滚动显示,那么最后一个单词就是最后出现的单词。
如果不存在最后一个单词,请返回 0 。
说明:一个单词是指仅由字母组成、不包含任何空格的最大子字符串。
示例:输入: " Hello World " 输出: 5
'''
class Solution ( object ) :
def _lengthOfLastWord ( self , s ) : # 调包
"""
:type s: str
:rtype: int
"""
if len ( s ) == 0 :
return 0
s = s . split ( ) # 通过指定分隔符对字符串进行切片,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等
if len ( s ) > 0 :
return len ( s [ - 1 ] )
return 0
# 上述做法一句话写法:
return len ( s . split ( ) [ - 1 ] ) if s . split ( ) else 0
def lengthOfLastWord ( self , s ) : # 从后往前找
"""
:type s: str
:rtype: int
"""
count = 0
for i in range ( len ( s ) - 1 , - 1 , - 1 ) :
if s [ i ] != " " :
while i > = 0 and s [ i ] != " " :
cnt + = 1
i - = 1
break
return count