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.
1using System;
2
3class Solution {
4 public int LengthOfLastWord(string s) {
5 string[] words = s.Trim().Split(' ');
6 return words[words.Length - 1].Length;
7 }
8
9 static void Main(string[] args) {
10 Solution solution = new Solution();
11 Console.WriteLine(solution.LengthOfLastWord("Hello World")); // Outputs 5
12 }
13}
The C# solution trims the input string, splits it by spaces to get words, and returns the length of the last word found.
The C solution navigates from the end of the string, skipping trailing spaces, and counts the length of the word in reverse.