[LeetCode] Top Interview 150 Problems Solving # 58 Length of Last Word

Ramhee YeonRamhee Yeon
1 min read

Understanding the Problem

A string is given. It has spaces in between. The task is to return the last string’s length. If the string is s = “Hello world”, the last string will be ”world” and its length will be 5, so return 5.

Approach

My approach will be to split(), get the last index and return length of it.

Solution

It was a simple problem. It would take a few lines without any help of the internal functions but it took one line with it.

First, split the string by space, then get the last index with [-1], then get the length of the last index with len().

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        return len(s.split()[-1])

Reflection

Nothing much to say about this. I was happy to see that this kind of a problem could show in interviews.

0
Subscribe to my newsletter

Read articles from Ramhee Yeon directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ramhee Yeon
Ramhee Yeon

South Korean, master's degree of AI. Programmer for LLM, app and web development. I am seeking opportunities to go to the USA and Canada, and Europe. I used to live in Frankfurt, Moscow, Pretoria, Baguio. Where to next?