[LeetCode]题解(python):058-Length of Last Word

题目来源:

  https://leetcode.com/problems/length-of-last-word/


 

题意分析:

  给出只包括大小写和空格的字符,输出最后一个单词的长度。


 

题目思路:

  从最后一个字符开始搜索,如果字符非空格,则往前推一位,直到不是空格,此时记录起始位置。然后继续搜索,直到遇到下一个空格或者到了第一个位置,记为终点位置。长度则为起始位置减去终止位置。


 

代码(python):

  

class Solution(object):
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        size = len(s)
        if size == 0:
            return 0
        i = -1;first = True;begin = -1
        for j in range(size):
            if s[i] != ' ':
                i -= 1;first = False
            elif first:
                i-= 1;begin = i
            else:
                break
        return begin - i
View Code

 


 

转载请注明出处:http://www.cnblogs.com/chruny/p/4988176.html

posted @ 2015-11-23 13:27  Ry_Chen  阅读(262)  评论(0编辑  收藏  举报