您的位置:首页 > 编程语言 > Python开发

Leetcode58. 最后一个单词的长度(python3)

2019-02-19 14:05 351 查看

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']
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: