Leetcode Length of Last Word problem solution

In the Leetcode Length of Last Word problem solution 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.

Constraints:

  • 1 <= s.length <= 104
  • s consists of only English letters and spaces ‘ ‘.
  • There will be at least one word in s.

Solution in C Programming

#include <stdio.h>
#include <string.h>

int lengthOfLastWord(char* s) {
    // trim the trailing spaces
    int p = strlen(s) - 1;
    while (p >= 0 && s[p] == ' ') {
        p--;
    }

    // compute the length of last word
    int length = 0;
    while (p >= 0 && s[p] != ' ') {
        p--;
        length++;
    }
    return length;
}

Solution in C++ Programming

class Solution {
public:
    int lengthOfLastWord(string s) {
        int len = 0, i;
        for(i=s.length()-1;i>=0;i--) {
            if(len && s[i] == ' ') return len;
            if(s[i] == ' ') continue;
            else len++;
        }
        return len;
    }
};

Solution in Java Programming

import java.util.*;

class Solution {
    public int lengthOfLastWord(String s) {
        StringTokenizer st = new StringTokenizer(s);
        String sub = "";
        while (st.hasMoreElements()) {
            sub = st.nextToken();
        }
        
        return sub.length();
    }
}

Solution in Python Programming

class Solution:
    # @param {string} s
    # @return {integer}
      def lengthOfLastWord(self, s):
        n = len(s)
        #print n
        if n == 1:
            if s[0] == ' ':
                return 0
            else:
                return 1
        
        count = 0
        if n==0:
            return 0
        for i in range(n-1,-1,-1):
            print 'kk: ',i,s[i]
            if s[i] != ' ':
                count += 1
            elif s[i] == ' ' and count > 0:
                return count
        return count

Solution in C# Programming

public class Solution {
    public int LengthOfLastWord(string s) {
        string[] words = s.Trim().Split(' ');
        return words[words.Length - 1].ToCharArray().Length;
    }
}

Also read,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *