Length of Last Word LeetCode Solution

Here, We see Length of Last Word LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Length of Last Word LeetCode Solution

Length of Last Word LeetCode Solution

Problem Statement

Given a string s consisting of words and 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.

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.

Length of Last Word Leetcode Solution C++

class Solution {
public:
    int lengthOfLastWord(string s) {
        int A = 0;
        for (int i=s.size()-1; i>=0; --i) {
            if (s[i] != ' ') ++A;
            else if (A) return A;
        }
        return A;        
    }
};Code language: PHP (php)

Length of Last Word Leetcode Solution Java

class Solution {
    public int lengthOfLastWord(String s) {
        int length = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
            if (s.charAt(i) != ' ') {
                length++;
            } else {
                if (length > 0) return length;
            }
        }
        return length;        
    }
}Code language: JavaScript (javascript)

Length of Last Word Leetcode Solution JavaScript

var lengthOfLastWord = function(s) {
    let trimmedString = s.trim();
    return trimmedString.length - trimmedString.lastIndexOf(' ') - 1;   
};Code language: JavaScript (javascript)

Length of Last Word Leetcode Solution Python

class Solution(object):
    def lengthOfLastWord(self, s):
        s = s.strip()       # Remove the spaces at the beginning and end
        length = 0
        for i in range(len(s)):
            if s[i] == " ":
                length = 0
            else:
                length += 1    # Inside one word
        return length
Scroll to Top