58. Length of Last Word
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)
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;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.