Length of last word in the string

Given a string s consisting of upper/lower-case alphabets and empty space characters ‘ ‘, return the length of the last word in the string. If the last word does not exist, return 0.

Examples:  

Input  : str = "Geeks For Geeks"
Output : 5
length(Geeks)= 5

Input : str = "Start Coding Here"
Output : 4
length(Here) = 4

Input  :  **
Output : 0

Approach 1: Iterate String from index 0 
If we iterate the string from left to right, we would have to be careful about the spaces after the last word. The spaces before the first word can be ignored easily. However, it is difficult to detect the length of the last word if there are spaces at the end of the string. This can be handled by trimming the spaces before or at the end of the string. If modifying the given string is restricted, we need to create a copy of the string and trim spaces from that.  

C++

#include <iostream>

#include <string>

using namespace std;

class GFG {

public:

    int lengthOfLastWord(const string& a) {

        int len = 0;

        string x = a;

        x.erase(0, x.find_first_not_of(" "));

        x.erase(x.find_last_not_of(" ") + 1);

        for (int i = 0; i < x.length(); i++) {

            if (x[i] == ' ')

                len = 0;

            else

                len++;

        }

        return len;

    }

};

int main() {

    string input = "Geeks For Geeks  ";

    GFG gfg;

    cout << "The length of last word is " << gfg.lengthOfLastWord(input) << endl;

    return 0;

}

Java

public class GFG {

    public int lengthOfLastWord(final String a)

    {

        int len = 0;

        String x = a.trim();

        for (int i = 0; i < x.length(); i++) {

            if (x.charAt(i) == ' ')

                len = 0;

            else

                len++;

        }

        return len;

    }

    public static void main(String[] args)

    {

        String input = "Geeks For Geeks  ";

        GFG gfg = new GFG();

        System.out.println("The length of last word is "

                           + gfg.lengthOfLastWord(input));

    }

}

Python3

def lengthOfLastWord(a):

    l = 0

    x = a.strip()

    for i in range(len(x)):

        if x[i] == " ":

            l = 0

        else:

            l += 1

    return l

if __name__ == "__main__":

    inp = "Geeks For Geeks "

    print("The length of last word is",

          lengthOfLastWord(inp))

C#

using System;

class GFG {

    public virtual int lengthOfLastWord(string a)

    {

        int len = 0;

        string x = a.Trim();

        for (int i = 0; i < x.Length; i++) {

            if (x[i] == ' ') {

                len = 0;

            }

            else {

                len++;

            }

        }

        return len;

    }

    public static void Main(string[] args)

    {

        string input = "Geeks For Geeks ";

        GFG gfg = new GFG();

        Console.WriteLine("The length of last word is "

                          + gfg.lengthOfLastWord(input));

    }

}

Javascript

<script>

function lengthOfLastWord(a)

{

    let len = 0;

    x = a.trim();

    for (let i = 0; i < x.length; i++) {

        if (x[i] == ' ') {

            len = 0;

        }

        else {

            len++;

        }

    }

    return len;

}

input = "Geeks For Geeks ";

document.write("The length of last word is "+ lengthOfLastWord(input));

</script>

Output

The length of last word is 5

Approach 2: Iterate the string from the last index. This idea is more efficient since we can easily ignore the spaces from the last. The idea is to start incrementing the count when you encounter the first alphabet from the last and stop when you encounter a space after those alphabets.

C++

#include <bits/stdc++.h>

#include <iostream>

using namespace std;

int length(string str)

{

    int count = 0;

    bool flag = false;

    for (int i = str.length() - 1; i >= 0; i--) {

        if ((str[i] >= 'a' && str[i] <= 'z')

            || (str[i] >= 'A' && str[i] <= 'Z')) {

            flag = true;

            count++;

        }

        else {

            if (flag == true)

                return count;

        }

    }

    return count;

}

int main()

{

    string str = "Geeks for Geeks";

    cout << "The length of last word is " << length(str);

    return 0;

}

Java

public class GFG {

    public int lengthOfLastWord(final String a)

    {

        boolean char_flag = false;

        int len = 0;

        for (int i = a.length() - 1; i >= 0; i--) {

            if (Character.isLetter(a.charAt(i))) {

                char_flag = true;

                len++;

            }

            else {

                if (char_flag == true)

                    return len;

            }

        }

        return len;

    }

    public static void main(String[] args)

    {

        String input = "Geeks For Geeks  ";

        GFG gfg = new GFG();

        System.out.println("The length of last word is "

                           + gfg.lengthOfLastWord(input));

    }

}

Python3

def findLength(str):

    count = 0

    flag = False

    for i in range(len(str) - 1, -1, -1):

        if ((str[i] >= 'a' and str[i] <= 'z') or (str[i] >= 'A' and str[i] <= 'Z')):

            flag = True

            count += 1

        elif (flag == True):

            return count

    return count

str = "Geeks for Geeks"

print("The length of last word is",

      findLength(str))

C#

using System;

class GFG {

    public virtual int lengthOfLastWord(string a)

    {

        bool char_flag = false;

        int len = 0;

        for (int i = a.Length - 1; i >= 0; i--) {

            if (char.IsLetter(a[i])) {

                char_flag = true;

                len++;

            }

            else {

                if (char_flag == true) {

                    return len;

                }

            }

        }

        return len;

    }

    public static void Main(string[] args)

    {

        string input = "Geeks For Geeks ";

        GFG gfg = new GFG();

        Console.WriteLine("The length of last word is "

                          + gfg.lengthOfLastWord(input));

    }

}

PHP

<?php

function length($str)

{

    $count = 0;

    $flag = false;

    for($i = strlen($str)-1 ; $i>=0 ; $i--)

    {

        if( ($str[$i] >='a' && $str[$i]<='z') ||

            ($str[$i] >='A' && $str[$i]<='Z'))

        {

            $flag = true;

            $count++;

        }

        else

        {

            if($flag == true)

                return $count;

        }

    }

    return $count;

}

$str = "Geeks for Geeks";

echo "The length of last word is ", length($str);

?>

Javascript

function length(str) {

    let count = 0;

    let flag = false;

    for (let i = str.length - 1; i >= 0; i--) {

        if ((str[i] >= 'a' && str[i] <= 'z')

            || (str[i] >= 'A' && str[i] <= 'Z')) {

            flag = true;

            count++;

        }

        else {

            if (flag == true)

                return count;

        }

    }

    return count;

}

let str = "Geeks for Geeks";

console.log(`The length of last word is ${length(str)}`);

Output

The length of last word is 5

Method #3 : Using split()  and list 

  • As all the words in a sentence are separated by spaces.
  • We have to split the sentence by spaces using split().
  • We split all the words by spaces and store them in a list.
  • Print the length of the last word of the list.

Below is the implementation:

C++

#include <iostream>

#include <string>

#include <vector>

using namespace std;

int length(string str) {

  vector<string> lis;

  string word = "";

  for (char c : str) {

    if (c == ' ') {

      lis.push_back(word);

      word = "";

    } else {

      word += c;

    }

  }

  lis.push_back(word);

  return lis.back().length();

}

int main() {

  string str = "Geeks for Geeks";

  cout << "The length of last word is " << length(str) << endl;

  return 0;

}

Java

import java.util.ArrayList;

import java.util.List;

public class Main {

    public static int length(String str) {

        List<String> lis = new ArrayList<>();

        String word = "";

        for (char c : str.toCharArray()) {

            if (c == ' ') {

                lis.add(word);

                word = "";

            } else {

                word += c;

            }

        }

        lis.add(word);

        return lis.get(lis.size() - 1).length();

    }

    public static void main(String[] args) {

        String str = "Geeks for Geeks";

        System.out.println("The length of last word is " + length(str));

    }

}

Python3

def length(str):

    lis = list(str.split(" "))

    return len(lis[-1])

str = "Geeks for Geeks"

print("The length of last word is",

      length(str))

Javascript

<script>

function length(str)

{

    var lis = str.split(" ")

    return lis[lis.length - 1].length;

}

var str = "Geeks for Geeks"

document.write("The length of last word is " +

               length(str));

</script>

C#

using System;

public class Program {

    static int length(string str)

    {

        string[] lis = str.Split(' ');

        return lis[lis.Length - 1].Length;

    }

    static void Main()

    {

        string str = "Geeks for Geeks";

        Console.WriteLine("The length of last word is "

                          + length(str));

    }

}

Output

The length of last word is 5

METHOD 4:Using regular expressions

APPROACH:

The regular expression essentially matches all non-space characters at the end of the string. The re.findall() function then returns a list of all non-overlapping matches in the input string, which in this case is just a single match consisting of the last word. Finally, the join() function is used to join the list of characters into a single string, and the length of this string (i.e., the length of the last word) is returned by the functio

ALGORITHM:

1.Import the re module for regular expressions
2.Use the findall() function to find all non-space characters at the end of the string
3.Join the resulting list of characters into a string
4.Return the length of the resulting string

Python3

import re

def length_of_last_word_4(s):

    last_word = ''.join(re.findall('[^ ]*$', s))

    return len(last_word)

s = "Geeks For Geeks"

print(length_of_last_word_4(s))

s = "Start Coding Here"

print(length_of_last_word_4(s)) 

s = ""

print(length_of_last_word_4(s))

Time complexity: O(n), where n is the length of the input string
Space complexity: O(n), where n is the length of the input string

This article is contributed by Saloni Baweja. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

There are lots of ways to achieve that. The most efficient approach is to determine the index of the last white space followed by a letter.

It could be done by iterating over indexes of the given string (reminder: String maintains an array of bytes internally) or simply by invoking method lastIndexOf().

Keeping in mind that the length of a string that could be encountered at runtime is limited to Integer.MAX_VALUE, it’ll not be a performance-wise solution to allocate in memory an array, produced as a result of splitting of this lengthy string, when only the length of a single element is required.

The code below demonstrates how to address this problem with Stream IPA and a usual for loop.

The logic of the stream:

  • Create an IntStream that iterates over the indexes of the given string, starting from the last.
  • Discard all non-alphabetic symbols at the end of the string with dropWhile().
  • Then retain all letters until the first non-alphabetic symbol encountered by using takeWhile().
  • Get the count of element in the stream.

Stream-based solution:

public static int getLastWordLength(String source) {
    return (int) IntStream.iterate(source.length() - 1, i -> i >= 0, i -> --i)
            .map(source::charAt)
            .dropWhile(ch -> !Character.isLetter(ch))
            .takeWhile(Character::isLetter)
            .count();
}

If your choice is a loop there’s no need to reverse the string. You can start iteration from the last index, determine the values of the end and start and return the difference.

Just in case, if you need to reverse a string that is the most simple and efficient way:

new StringBuilder(source).reverse().toString();

Iterative solution:

public static int getLastWordLength(String source) {
    int end = -1; // initialized with illegal index
    int start = 0;
    for (int i = source.length() - 1; i >= 0; i--) {
        if (Character.isLetter(source.charAt(i)) && end == -1) {
            end = i;
        }
        if (Character.isWhitespace(source.charAt(i)) && end != -1) {
            start = i;
            break;
        }
    }
    return end == -1 ? 0 : end - start;
}

main()

public static void main(String[] args) {
    System.out.println(getLastWord("Humpty Dumpty sat on a wall  % _ (&)"));
}

output

4   -   last word is "wall"

Introduction

I am still on the journey of solving at least one Data Structures and Algorithm question daily on Leetcode in order to understand the concepts I am learning well and it has been very challenging and interesting since I started solving these questions.

This article will explain my solution to Length of Last Word in a String on Leetcode and the logic behind my solution. Try to follow it step by step and I am sure you will understand every bit of it.

Let’s dive into it 🎉

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

  • Input: s = «Hello World»
  • Output: 5
  • Explanation: The last word is «World» with length 5.

Step by Step Solution

Solving a Data Structures and Algorithm question requires you to think well and check your solution using different scenarios because your solution must pass all the test cases before it can be accepted.

We will solve this problem in 2 steps, which are:

  • Doing Sanity Checks.
  • Explaining the Logic behind our solution and writing the Code to back it up.

Sanity Checks

Before proceeding to carry out any operation we have to check the input passed to the function if it is valid. so let’s do a minor check that if it is not valid.

 // Sanity Checks
    if (!s) {
        return s;
    }

The last check is if the length of the string is 1, just return the length of the string directly because it is also the last word.

  if(s.length <= 1) {
        return s.length;
    }

But if none of these conditions is met then we can proceed to carry out the main operation.

Solution Logic

The Solution to this question will be in steps for easy understanding.

  • Trim the string with the trim method trim() in order to remove whitespaces from the left and right sides of the string.

  • After removing the whitespaces with trim then we can now turn the string to an array so that it will be very easy to get the last value of the array by index.

  • To turn the string to array, we will use the split method split(" "). There must be space between the double quote so that it can split it by words, if there is no space between the quote it will split it by character.

s.trim().split(" ");
  • Let’s store this new array in a variable called arrStr
    let arrStr = s.trim().split(" ");
    
  • The next thing is to get the last item in the array of words, we can get it by the index and to get the index of the last item in every array the index is always the length of the array — 1 because array starts the index from 0.

  • So since the index is [arrStr.length - 1]. then the last item of the array can now be gotten like this

arrStr[arrStr.length - 1]
  • Since we have gotten the last item, we can just use the .length method to get the length.
arrStr[arrStr.length - 1].length;
  • Lastly, return the length of the last word.
return arrStr[arrStr.length - 1].length;

The Time and Space Complexity

Time Complexity

This Solution has a Time complexity of O(n) which is a Linear time since we are splitting the string to an array and it depends on the length of the string.

Space complexity

The Space Complexity is also O(n) since we are using extra space to store the words in an array.

The Runtime is 60ms, faster than 98.80% of JavaScript online submissions for Length of Last Word and Memory Usage: 38.8 MB, less than 47.63% of JavaScript online submissions.

Length of Last Word Solution.JPG

Conclusion

I hope you have learnt a lot from this article and your contribution is also highly welcomed because we get better by learning from others, you can reach out to me on Twitter here. Watch out for more helpful contents on Data Structures and Algorithm from me.

Don’t forget to Like, share and subscribe for more articles in this series called Solutions to Data Structures and Algorithm Questions on Leetcode.

Enjoy 🎉

Welcome back, LeetCoders! Today I’ll be tackling problem #58, which is called Length of Last Word. From the description:

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.

Now, there’s a clean way and a not so clean way to accomplish the task we’re given. Being the person I am, I’m going to go the easy route.

My thoughts on solving this problem were to simply strip the whitespace off the ends of the string, then to split it into an array and grab the length of the last word. A bigger challenge would be to deal with all of the spaces in an efficient manner so we’re only left with the words in the array and not random spaces — but I’m solving it the quick and dirty way, which is to only strip what we need.

So let’s get started. We’re given a string s, so we’ll start by just having the function return the string (makes it easier to debug).

var findLengthOfLastWord = function(s) {
   return s;
}

Enter fullscreen mode

Exit fullscreen mode

Now, let’s incorporate some of the logic we talked about. We need to 1) strip both ends of the string, 2) split it into an array, 3) grab the last element of the array, and 4) return that element’s length. Fortunately, there’s a one-liner that does the job.

return s.trim().split(' ').slice(-1)[0].length;

Enter fullscreen mode

Exit fullscreen mode

You could also use trimEnd() instead of trim(), because if you think about it, the only trimming we need to do is from the end so we know what the true last word is. Both are about the same speed though, so I’ll leave it with trim().

So there you have it. A truly janky solution to a classic LeetCode problem.

var lengthOfLastWord = function(s) {
   return s.trim().split(' ').slice(-1)[0].length;
};

Enter fullscreen mode

Exit fullscreen mode

As always, code can be found in the Github repository.
Happy coding!

Description

LeetCode Problem 58.

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:

1
2
3
Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.

Example 2:

1
2
3
Input: s = "   fly me   to   the moon  "
Output: 4
Explanation: The last word is "moon" with length 4.

Example 3:

1
2
3
Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.

Constraints:

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

Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
    /* Start from the tail of s and move backwards to find the first non-space character. 
    Then from this character, move backwards and count the number of non-space characters 
    until we pass over the head of s or meet a space character. The count will then be the 
    length of the last word. */
    int lengthOfLastWord(string s) { 
        int len = 0, tail = s.length() - 1;
        while (tail >= 0 && s[tail] == ' ') tail--;
        while (tail >= 0 && s[tail] != ' ') {
            len++;
            tail--;
        }
        return len;
    }
};


08 Nov 2021

Related Posts

Like this post? Please share to your friends:
  • Len формула excel на русском
  • Len в excel что это
  • Len excel формула по русски
  • Legal definition of word any
  • Legal definition of the word will