# 58. Length of Last Word 🔠

**Difficulty**: `Easy` - **Tags**: `String`

[LeetCode Problem Link](https://leetcode.com/problems/length-of-last-word/description/)

## Description

Given a string `s` consisting of words and spaces, return the length of the last word in the string.

A word is defined as a maximal substring consisting of non-space characters only.

## Examples

**Example 1:**

Input:

```java
s = "Hello World"
```

Output:

```
5
```

Explanation: The last word is "World" which has a length of 5.

**Example 2:**

Input:

```java
s = "   fly me   to   the moon  "
```

Output:

```
4
```

Explanation: The last word is "moon" with a length of 4.

**Example 3:**

Input:

```java
s = "luffy is still joyboy"
```

Output:

```
6
```

Explanation: The last word is "joyboy" which has a length of 6.

## Constraints

* The input string `s` consists of only printable ASCII characters.
* The string may contain leading or trailing spaces, but it will not contain multiple consecutive spaces.

## Solution 💡

To solve this problem, we trim the string to remove any leading or trailing spaces, then count the characters of the last word by iterating from the end of the string until we encounter a space.

### Java

```java
class Solution {
    public int lengthOfLastWord(String s) {
        String trimmedString = s.trim();
        int length = 0;
        
        for (int i = trimmedString.length() - 1; i >= 0; i--) {
            if (trimmedString.charAt(i) == ' ') {
                break;
            }
            length++;
        }
        
        return length;
    }
}
```

### Time Complexity ⏳

* **O(n)**: The time complexity is linear, where `n` is the length of the trimmed input string.

### Space Complexity 💾

* **O(1)**: The space complexity is constant as we only use a few variables.

You can find the full solution [here](https://github.com/ChunhThanhDe/Leetcode-Top-Interview/blob/main/Topic%201%20Array%20-%20String/019%20Length%20of%20Last%20Word/Solution.java).


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://chunhthanhde.gitbook.io/leetcode-top-interview/topic-1-array-string/019-length-of-last-word.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
