问题:给你一个字符串 s,由若干单词组成,单词之间用空格隔开。返回字符串中最后一个单词的长度。如果不存在最后一个单词,请返回 0 。
单词 是指仅由字母组成、不包含任何空格字符的最大子字符串。
示例 1:
输入:s = “Hello World”
输出:5
示例 2:
输入:s = " "
输出:0
提示:
1 <= s.length <= 104
s 仅有英文字母和空格 ’ ’ 组成
解法:
1.循环:
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
while True:
try:
in_str = s
if len(in_str) > 10000 or len(in_str) == 0:
raise Exception
last = in_str.strip().split(" ")[-1]
leng = len(last)
return leng
break
except Exception:
print("0")
2.或不带循环:
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
try:
in_str = s
if len(in_str) > 10000 or len(in_str) == 0:
raise Exception
last = in_str.strip().split(" ")[-1]
leng = len(last)
return leng
except Exception:
print("0")
3.不带try和except,最简单:
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
in_str = s
if len(in_str) > 10000 or len(in_str) == 0:
print("0")
last = in_str.strip().split(" ")[-1]
#strip()必须要有,需要移除测试用例字符串中首尾的空格。
leng = len(last)
return leng
strip()的用法:
str = "00000003210Runoob01230000000";
print str.strip( '0' ); # 去除首尾字符 0
str2 = " Runoob "; # 去除首尾空格
print str2.strip();