LeetCode: 58. Length of Last Word

The Problem

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

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

Example

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.

The solution

We opted for a simple approach using a for loop, this was the result:

int lengthOfLastWord(string s) {
	int ans = 0;
	for(int i = s.size() - 1; i >= 0; --i )
		if(s[i] != ' ') ++ans;
		else if(ans > 0) break;

	return ans;
}
🧠
Github with all the solution including test cases.

Let's break it down:

int lengthOfLastWord(string s):

  • This line declares a function named lengthOfLastWord that takes a string s as input and returns an integer.

int ans = 0;:

  • This line initializes a variable named ans with the value 0. This variable will be used to store the length of the last word in the string s.

for(int i = s.size() - 1; i >= 0; --i):

  • This is a for loop that iterates over the characters of the string s in reverse order, starting from the last character and going backwards until the first character.

if(s[i] != ' ') ++ans;:

  • Inside the loop, this if statement checks if the current character s[i] is not a space.
  • If the character is not a space, it means it belongs to the last word, so the ans variable (which stores the length of the last word) is incremented by 1.

else if(ans > 0) break;:

  • If the current character is a space and the length of the last word (ans) is greater than 0, it means we have encountered the end of the last word and the beginning of the space after it.
  • In this case, we exit the loop using the break statement because we have already found the last word and there's no need to continue iterating.

return ans;:

  • Finally, the function returns the value stored in the ans variable, which represents the length of the last word in the string s.