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.
题目分析:计算输入的字符串中最后一个单词的长度。
示例: Input: “Hello World” Output:5
需要考虑的问题: 1.输入的字符串结尾是空格 2.输入的字符串为空。
方法一:
- 这道题挺简单的,基本没什么难度。所以懒得去做过多的说明了,代码在下面。
- 代码:
class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
n=0
i=len(s)-1
while i>=0 and s[i]==' ':
i-=1
while i>=0 and s[i]!=' ':
n+=1
i-=1
return n
可以清楚的看出我写的代码运行速度太慢了,所以就看了一下别人的写的又快有短的。其实思路基本上是一样的。我贴在下面了,以供参考。
方法二:
大多用到了Python中的split方法,它的用法这个链接里(Python3 split())有详细说明。
- 代码1:
class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
if len(s) == 0:
return 0
# get all words into an array
words = s.split()
# get the last word
word = words[-1:]
if len(word) > 0:
# remove all non-desired characters
result = word[0].strip(" !@#$%^&*()-_+={}[]|\:;'<>?,./\"")
return len(result)
else:
return 0
- 代码2:
class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
trimmed = s.strip()
if len(trimmed)>0:
return len(trimmed.split(" ")[-1])
else:
return 0
- 代码3:
class Solution:
def lengthOfLastWord(self, s):
a = s.split()
if len(a) == 0:
return 0
if len (a) == 1:
return len(a[0])
x = a[-1]
return(len(x))
- 代码4:
class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
s = s.split()
if s == []:
return 0
else:
return len(s[-1])