标签:
https://leetcode.com/problems/length-of-last-word/
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.
For example,
Given s = “Hello World”,
return 5.
给定一个字符串s,只包含大小写字母和空格字符 ‘ ‘
,返回该字符串中最后一个单词的长度。如果不存在最后一个单词返回0。
注意:所谓单词,是指仅由非空格字符组成的字符序列。比如,给定s= “Hello World”
,返回 5
。
利用Python的内置函数string.rstrip()和string.split()。先将字符串后面的空格部分删除,再按照空格字符将剩余部分分成若干部分,此时最后一部分即为最后一个单词(也可能是”),直接返回其长度即可。
代码
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
return len(s.rstrip().split(‘ ‘)[-1])
与上面类似,不过不再用内置string处理函数了,在删除后面的空格后,从后面开始数非空格字符的个数,即为所求。
代码
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
PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/51702268
58. Length of Last Word [easy] (Python)
标签:
原文地址:http://blog.csdn.net/coder_orz/article/details/51702268