LeetCode 58: Length of Last Word Solution
Master LeetCode problem 58 (Length of Last Word), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
58. Length of Last Word
Problem Explanation
Explanation
To find the length of the last word in a given string, we can iterate through the string in reverse order. We skip any trailing spaces and then count characters until we encounter a space or reach the beginning of the string.
- Start iterating from the end of the string.
- Skip any trailing spaces.
- Count characters until a space is encountered or the beginning of the string is reached.
- Return the count as the length of the last word.
Time Complexity: O(n) where n is the length of the input string.
Space Complexity: O(1)
Solution Code
class Solution {
public int lengthOfLastWord(String s) {
int length = 0;
int n = s.length();
int i = n - 1;
while (i >= 0 && s.charAt(i) == ' ') {
i--;
}
while (i >= 0 && s.charAt(i) != ' ') {
length++;
i--;
}
return length;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 58 (Length of Last Word)?
This page provides optimized solutions for LeetCode problem 58 (Length of Last Word) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 58 (Length of Last Word)?
The time complexity for LeetCode 58 (Length of Last Word) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 58 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 58 in Java, C++, or Python.