Coding

# Leetcode Length of Last Word solution

5
(1)

Given a string `s` consisting of some words separated by some number of spaces, return the length of the last word in the string.

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

Solution

I would admit that after a long time, I was able to solve a leetcode problem in about 5 minutes. Hurray. 🙂 . May be it was because of morning freshness. Let me write my approach. We want to find length of last word. So we can start reading string from backwards and increment a counter till we get a space. Then we can return the counter. But there is one problem. What if you have leading and trailing spaces in the string. Something like ” This is sample “. Then what you can do is strip the leading and trailing spaces and then use the same approach and it will work.

``````class Solution {
public int lengthOfLastWord(String s) {
int lastLen = 0;
s = s.strip();
for (int i=0; i<s.length(); i++) {
char c = s.charAt(s.length()-i-1);
if (c == ' ') break;
lastLen++;
}

return lastLen;
}
}``````

The solution above is 100% faster than all the Java online submissions. Happy coding. 🙂

Click on a star to rate it!

Average rating 5 / 5. Vote count: 1

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post? 