58. Length of Last Word [easy] (Python)

题目链接

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值