# Length of Last Word

## [Length of Last Word](https://leetcode.com/problems/length-of-last-word)

Given a string `s` consists of some words separated by spaces, return *the length of the last word in the string. If the last word does not exist, return* `0`.

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

**Example 1:**

```
Input: s = "Hello World"
Output: 5
```

**Example 2:**

```
Input: s = " "
Output: 0
```

**Constraints:**

* `1 <= s.length <= 104`
* `s` consists of only English letters and spaces `' '`.

## Solutions

### 🐍 Python

```python
class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        return len(s.rsplit(maxsplit=1)[-1]) if len(s.strip()) else 0
```

### 🧠 Cpp

```cpp
class Solution {
public:
    int lengthOfLastWord(string s)
    {
        int counter = 0;
        auto riter = s.rbegin();
        for(; *riter == ' '; riter++);
        for(; *riter!=' ' && riter!=s.rend(); riter++, counter++);
        return counter;
    }
};
```


---

# 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://anton-veselskyi.gitbook.io/codding-problems-solutions/leetcode/easy/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.
