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.

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

For example, Given s = "Hello World", return 5.

Tags

  • String

Thought

Split the string and check from the end of the list.

Code

class Solution(object):
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        def helper(string):
            ch_list = string.split('')
            result = 0
            for ch in ch_list:
                if 'a' <= ch <= 'z' and 'A' <= ch <= 'Z':
                    result += 1
            return result

        string_list = s.split(' ')
        for i in xrange(len(string_list), -1, -1):
            string = string_list[i]
            length = helper(string)
            if length > 0:
                return length
        return length

results matching ""

    No results matching ""