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.
1#include <stdio.h>
2#include <string.h>
3
4int lengthOfLastWord(char * s) {
5 int length = 0;
6 for (int i = strlen(s) - 1; i >= 0; i--) {
7 if (s[i] == ' ' && length > 0) {
8 break;
9 }
10 if (s[i] != ' ') {
11 length++;
12 }
13 }
14 return length;
15}
16
17int main() {
18 char str[] = "Hello World";
19 printf("%d\n", lengthOfLastWord(str)); // Outputs 5
20 return 0;
21}
The C solution trims trailing spaces from the end first by iterating backward, and counts non-space characters to find the length of the last word.
This approach involves traversing the string from the end, skipping spaces, and then counting the length of the last word by scanning backward.
Time Complexity: O(n)
Space Complexity: O(1)
1#include <iostream>
2using namespace std;
3
int lengthOfLastWord(string s) {
int length = 0, i = s.length() - 1;
while (i >= 0 && s[i] == ' ') i--; // Skip trailing spaces
while (i >= 0 && s[i] != ' ') {
length++;
i--;
}
return length;
}
int main() {
string str = "luffy is still joyboy";
cout << lengthOfLastWord(str) << endl; // Outputs 6
return 0;
}
The C++ solution steps backward through the string, avoiding trailing spaces, to calculate the last word's length.