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 <iostream>
2#include <sstream>
3using namespace std;
4
5int lengthOfLastWord(string s) {
6 istringstream ss(s);
7 string word;
8 while (ss >> word) {}
9 return word.size();
10}
11
12int main() {
13 string str = "Hello World";
14 cout << lengthOfLastWord(str) << endl; // Outputs 5
15 return 0;
16}
This solution uses an input string stream to split the string into words and outputs the length of the last word.
The C solution navigates from the end of the string, skipping trailing spaces, and counts the length of the word in reverse.