🎀 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:
Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.
👩💻 My Answer
class Solution {
public int lengthOfLastWord(String s) {
boolean check = true;
int count = 0;
for (int i = 0; i < s.length(); i++) {
char letter = s.charAt(i);
if (check && letter != ' ')
count++;
else if (!check && letter != ' ') {
count = 1;
check = true;
}
else
check = false;
}
return count;
}
}
Pro & Con
- ✅ Memory
- ✖️ Runtime
💋 Ideal Answer
Approach
I read the solution post on LeetCode and found it is better to iterate backward because we are looking for the LAST word.
New Code
class Solution {
public int lengthOfLastWord(String s) {
int count = 0;
for (int i = s.length() - 1; i >= 0; i--) {
char letter = s.charAt(i);
if (letter != ' ') {
count++;
} else if (count != 0 && letter == ' ')
return count;
}
return count;
}
}
💡 What I Learned
Iterate backward!!! If you only care about the LAST word, iterate backward! The direction of iteration matters!
ALSO! You don't need boolean to check. You can just use COUNTER (integer) of the letter. If its 0, then ' ' is just the one after the last word. If its more than 0, then ' ' is the one between the second last and last one!
Top comments (0)