LeetCode Python/Java/C++/JS  >  58. Length of Last Word  >  Solved in Python, Ruby, Java, C++, C#, JavaScript, Go  >  GitHub

LeetCode link: 58. Length of Last Word, difficulty: Easy.

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 <= 10^4
  • s consists of only English letters and spaces ' '.
  • There will be at least one word in s.
Topics

String

Intuition

  • To find the length of the last word, we can use methods like split(), last(), and len().
  • However, this kind of problem is actually meant to test a programmer’s ability to control index.
  • Since the last word is at the end, solving it from the front isn’t very convenient. Is there another way?

Click to view the answer


You can solve this by traversing the string backwards. There are only two cases to consider: whether the current character is a space or not.

  • Initially, if you encounter a space, skip it and move to the next character. If you encounter a non-space character, increment the length.
  • If length > 0, it means you have already encountered letters. At this point, if the current character is a space, you can return the result.

👋 Hi, I'm the developer behind coder.id — Build your programmer brand. Create your portfolio, resume, and blog in minutes, and land your dream offer!

Complexity

Time complexity

O(N)

Space complexity

1

Python #

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        length = 0

        for i in range(len(s) - 1, -1, -1):
            if s[i] == " ":
                if length > 0:
                    return length
                continue

            length += 1

        return length

Ruby #

# @param {String} s
# @return {Integer}
def length_of_last_word(s)
  length = 0

  (s.size - 1).downto(0) do |i|
    if s[i] == " "
      return length if length > 0
      next
    end

    length += 1
  end

  length
end

Java #

class Solution {
    public int lengthOfLastWord(String s) {
        int length = 0;

        for (int i = s.length() - 1; i >= 0; i--) {
            if (s.charAt(i) == ' ') {
                if (length > 0) {
                    return length;
                }
                continue;
            }

            length++;
        }

        return length;
    }
}

C++ #

class Solution {
public:
    int lengthOfLastWord(string s) {
        int length = 0;
        int n = s.size();

        for (int i = n - 1; i >= 0; i--) {
            if (s[i] == ' ') {
                if (length > 0) {
                    return length;
                }
                continue;
            }

            length++;
        }

        return length;
    }
};

C# #

public class Solution {
    public int LengthOfLastWord(string s) {
        int length = 0;

        for (int i = s.Length - 1; i >= 0; i--) {
            if (s[i] == ' ') {
                if (length > 0) {
                    return length;
                }
                continue;
            }

            length++;
        }

        return length;
    }
}

JavaScript #

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLastWord = function (s) {
    let length = 0;

    for (let i = s.length - 1; i >= 0; i--) {
        if (s[i] === " ") {
            if (length > 0) {
                return length;
            }
            continue;
        }

        length++;
    }

    return length;
};


Go #

func lengthOfLastWord(s string) int {
    length := 0

    for i := len(s) - 1; i >= 0; i-- {
        if s[i] == ' ' {
            if length > 0 {
                return length
            }
            continue
        }

        length++
    }

    return length
}

Other languages

Welcome to contribute code to GitHub repo -> 58. Length of Last Word. Thanks!

Level Up Your Developer Identity

  • 📄 Resume, Portfolio & Blog
  • 🌐 Custom Domain Binding Supported
  • ✨ Premium Subdomain: https://yourname.coder.id

Build Your Developer Brand at coder.id →