难度: Easy
原题连接
内容描述
Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
Example:
Input: "Hello World"
Output: 5
思路 1 - 时间复杂度: O(N)- 空间复杂度: O(N)******
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])
简单优化
class Solution:
def lengthOfLastWord(self, s: str) -> int:
return len(s.split()[-1])
思路 2
去除末尾空格,然后反转字符串,直接统计前非空字符即可
class Solution:
def lengthOfLastWord(self, s: str) -> int:
l = 0
for v in s.rstrip()[::-1]:
if v != ' ':
l += 1
else:
break
return l