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