Length of Last Word

Question

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.

Have you met this question in a real interview? Yes
Example
Given s = "Hello World", return 5.

Note
A word is defined as a character sequence consists of non-space characters only.

题解 1

class Solution:
    # @param s, a string
    # @return an integer
    def lengthOfLastWord(self, s):
        return len(s.split()[len(s.split())-1]) if s.split() != [] else 0

题解 2

直接从后向前扫描

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

results matching ""

    No results matching ""