Leetcode 58. Length of Last Word
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.
0
.trim()
method to remove leading and trailing spaces.Let’s go ahead and implement the solution in Java.
public class Solution {
public int lengthOfLastWord(String s) {
// Trim the string to remove leading and trailing spaces
s = s.trim();
// Handle edge case where the string is empty
if (s.isEmpty()) {
return 0;
}
// Split the string by spaces
String[] words = s.split(" ");
// Get the last word
String lastWord = words[words.length - 1];
// Return the length of the last word
return lastWord.length();
}
}
n
is the length of the string.Overall, the time complexity for the solution is O(n).
This solution efficiently computes the length of the last word in the given string with linear time complexity regarding the length of the input string.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?