Similar Problems

Similar Problems not available

Length Of Last Word - Leetcode Solution

Companies:

LeetCode:  Length Of Last Word Leetcode Solution

Difficulty: Easy

Topics: string  

Length Of Last Word is a problem on LeetCode where you are given a string, and you are required to find the length of the last word present in that string. Here is the detailed solution to the problem:

Problem Statement:

Given a string s consisting of only uppercase/lowercase English alphabets and whitespace characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string.

If the last word does not exist, return 0.

A word is defined as 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 = " " Output: 0 Explanation: There is no last word in a string consisting of a single space.

Solution:

To solve this problem, we will follow these steps:

  1. Trim the input string s to remove any leading or trailing whitespace characters.
  2. Split the trimmed string into an array of words using whitespace as a separator.
  3. If there are no words in the array, return 0.
  4. Otherwise, return the length of the last word in the array.

Let's implement the solution in Python:

class Solution: def lengthOfLastWord(self, s: str) -> int: # step 1: trim the input string s = s.strip() # step 2: split the trimmed string into an array of words words = s.split() # step 3: check if there are any words in the array if len(words) == 0: return 0 # step 4: return the length of the last word in the array return len(words[-1])

The time complexity of this solution is O(n), where n is the length of the input string s. The space complexity is also O(n), as we create a new array of words from the trimmed string.

Length Of Last Word Solution Code

1