Sponsored
Sponsored
This approach involves trimming any trailing spaces from the string, splitting it into words using spaces as delimiters, and then simply returning the length of the last word in the resulting list of words.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1), no extra space is used besides counters.
1class Solution {
2 public int lengthOfLastWord(String s) {
3 String[] words = s.trim().split(" ");
4 return words[words.length - 1].length();
5 }
6
7 public static void main(String[] args) {
8 Solution solution = new Solution();
9 System.out.println(solution.lengthOfLastWord("Hello World")); // Outputs 5
10 }
11}
The Java solution first trims the string, splits it into words and then returns the length of the last word from the string array.
The C solution navigates from the end of the string, skipping trailing spaces, and counts the length of the word in reverse.