058 length of last word
58. Length of Last Word
题目: https://leetcode.com/problems/length-of-last-word/
难度 : Easy
我的解法:
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
s = s[::-1].strip()
return s.find(' ') if s.find(' ') != -1 else len(s)
作弊式做法
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
lst = s.split()
if len(lst) >= 1:
return len(lst[-1])
return 0
split()方法最低可以分0组,split(' ')最低可以分1组
一行解法:
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
return len(s.strip().split(" ")[-1])