[LeetCode] 58. Length of Last Word_Easy tag: String

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.

Example:

Input: "Hello World"
Output: 5

就先利用s.strip()将前后的space去掉, 然后再用split(' ') 将最后的word的length得到并返回.

Code

class Solution:
    def lengthOfLastWord(self, s):
        s = s.strip()
        if not s: return 0
        return len(s.split(' ')[-1])

猜你喜欢

转载自www.cnblogs.com/Johnsonxiong/p/9496677.html