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
思路:先把字符串最后的空格去掉,再统计最后一个词的长度
解法一:用内置python函数
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
return len(s.rstrip().split(' ')[-1])解法二:不用内置函数class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
length, j = 0, len(s)-1
while j>=0:
if s[j] != ' ':
break
j = j - 1
for i in xrange(j, -1, -1):
if s[i] == ' ':
return length
length = length + 1
return length
本文介绍了一种通过去除字符串尾部空白字符并计算最后一个单词长度的方法。提供了两种解决方案:一种利用Python内置函数,另一种则不使用内置函数实现。
408

被折叠的 条评论
为什么被折叠?



