current position:Home>leetcode 58. Length of Last Word(python)

leetcode 58. Length of Last Word(python)

2022-01-29 15:39:29 Wang Daya

Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities .

describe

Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string.

A word is a maximal substring consisting of non-space characters only.

Example 1:

Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.
 Copy code 

Example 2:

Input: s = "   fly me   to   the moon  "
Output: 4
Explanation: The last word is "moon" with length 4.
 Copy code 

Example 3:

Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.
 Copy code 

Note:

1 <= s.length <= 10^4
s consists of only English letters and spaces ' '.
There will be at least one word in s.
 Copy code 

analysis

According to the meaning , Gives a string s , It is composed of several lowercase English words and spaces , Ask us to return the length of the last lowercase English word . In fact, the words here are not words in the strict sense , Just a substring composed of non spaces . The idea is simple , This problem is to investigate the processing of spaces in strings and the segmentation of strings , I use it directly python Built in functions strip Remove first s Spaces at both ends , And then use split Functions are separated by spaces s Get a list of substrings , The last element of the list must be the word , Find its length .

Of course, you can also use built-in functions , By traversing the string s It can also be solved , In short, this problem is relatively simple , I also use built-in functions to quickly brush questions .

answer

class Solution(object):
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        return len(s.strip().split(' ')[-1])

        	      
		
 Copy code 

Running results

Runtime: 32 ms, faster than 12.29% of Python online submissions for Length of Last Word.
Memory Usage: 13.7 MB, less than 55.34% of Python online submissions for Length of Last Word.
 Copy code 

Original link :leetcode.com/problems/le…

Your support is my greatest motivation

copyright notice
author[Wang Daya],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201291539272797.html

Random recommended