跳至主要內容

Leetcode 58. Length of Last Word

Given a string s consisting of words and spaces, return the length of the last word in the string.

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.

Example 2:

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

Example 3:

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

It’s a simple question, not too much to explain about it.

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        last_length = 0
        current_length = 0
        
        for character in s:
            if character != " ":
                current_length += 1
            else:
                current_length = 0
            
            if current_length != 0:
                last_length = current_length

        return last_length

UPDATE on 2024/04/05:

It can be faster by counting reversely since we only need to know the length of last word.

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        count = 0

        for i in range(len(s), 0, -1):
            if s[i-1] == ' ' and count != 0:
                return count
            elif s[i-1] != ' ':
                count += 1
        
        return count
分類:ArrayLeetcode

搶先發佈留言

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

由 Compete Themes 設計的 Author 佈景主題