DEV Community

Isaac Tonyloi
Isaac Tonyloi

Posted on

3 2

Length of Last Word

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.
Enter fullscreen mode Exit fullscreen mode

Example 2:

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

Example 3:

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

Constraints:

1 <= s.length <= 104
s consists of only English letters and spaces ' '.
There will be at least one word in s.
Enter fullscreen mode Exit fullscreen mode

Python solution

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

        length = 0

        new_str = s.strip()

        for i in range(len(new_str)):
            if new_str[i] == " ":
                length = 0
            else:
                length +=1
        return length


Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay