Leetcode58. 最后一个单词的长度
题目描述:
给定一个仅包含大小写字母和空格 ’ ’ 的字符串,返回其最后一个单词的长度。
如果不存在最后一个单词,请返回 0 。
说明:一个单词是指由字母组成,但不包含任何空格的字符串。
示例:
输入: “Hello World”
输出: 5
解法1:
class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
gap = s.split()
if not gap or gap[-1] =="":
return 0
return len(gap[-1])
解法2:
class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
ans = 0
length = 0
for i in s:
if i == ' ':
if length > 0:
ans = length
length = 0
else:
length += 1
return length if length>0 else ans
补充:
描述:Python split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串。
示例:
str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print str.split( ); # 以空格为分隔符,包含 \n
print str.split(' ', 1 ); # 以空格为分隔符,分隔成两个
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
txt = "Google#Runoob#Taobao#Facebook"
# 第二个参数为 1,返回两个参数列表
x = txt.split("#", 1)
print x
['Google', 'Runoob#Taobao#Facebook']