---
# System prepended metadata

title: 'Length of Last Word <img src="https://img.shields.io/badge/-easy-brightgreen">'
tags: [data_structure_python]

---

---
tags: data_structure_python
---

# Length of Last Word <img src="https://img.shields.io/badge/-easy-brightgreen">

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string.

If the last word does not exist, return 0.

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

<ins>**Example:**</ins>

>Input: "Hello World"
>Output: 5

## Solution

```python=
class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        n = len(s)
        
        if n == 0: # Case: ""
            return 0
        else:
            i = 0
            if s[n-1-i] == ' ': # Case: "ba c a  "
                while i < n and s[n-1-i] == ' ':
                    i += 1
                count = 0
                while i < n and s[n-1-i] != ' ':
                    i += 1
                    count += 1
                return count
                    
            else:
                while i < n and s[n-1-i] != ' ':
                    i+=1
                return i
```