Length of Last Word in Java (LeetCode 58): Strings
At first glance, LeetCode 58 (Length of Last Word) looks like it needs a full split() call, an array of tokens, and some bounds-checking. It doesn't. Because you only care about the word at the very end of the string, you can walk backward from the last index and stop the moment you hit a space after counting letters. No splitting, no extra array, just one backward pass. In this post I'll break down why scanning from the back works, dry-run it against a few tricky inputs (trailing spaces included), and then share clean Java for it. There's also a small interactive walker below so you can step through the backward scan character by character. Video Walkthrough Prefer to watch it instead? Here's the full walkthrough, from reading the problem to submitting the solution: 1. What the Problem Asks You're given a string s made of letters and spaces. A "word" is a maximal run of non-space characters. The task is to return the ...