评论区最多的就是it's no fun at all!哈哈哈
题目:
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
solution:
class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
if s is None:
return 0
j = s.strip().split(' ')
return len(j[-1])
当然也有那么一些大佬愿意不用函数:
用==' '或者.isspace()来判断最后一个空格后的那个单词的长度:
def lengthOfLastWord(self, s):
ls = len(s)
# slow and fast pointers
slow = -1
# iterate over trailing spaces
while slow >= -ls and s[slow] == ' ':
slow-=1
fast = slow
# iterate over last word
while fast >= -ls and s[fast] != ' ':
fast-=1
return slow - fast
def lengthOfLastWord(self, s):
# (going backwards) find first non-space char
for i in range(len(s) - 1, -2, -1):
if i == -1 or s[i] != " ":
break
# keep going until a space or end of string
for j in range(i, -2, -1):
if j == -1 or s[j] == " ":
return i - j
对不起,我庸俗~~~
等待大佬们去丰富吧https://leetcode.com/problems/length-of-last-word/discuss/21961/My-36-ms-Python-solution