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.
Example 1:
Input: s = "Hello World" Output: 5 Explanation: The last word is "World" with length 5.
Example 2:
Input: s = " fly me to the moon " Output: 4 Explanation: The last word is "moon" with length 4.
Example 3:
Input: s = "luffy is still joyboy" Output: 6 Explanation: The last word is "joyboy" with length 6.
Constraints:
1 <= s.length <= 104sconsists of only English letters and spaces' '.- There will be at least one word in
s.
Approach 01:
-
C++
-
Python
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int lengthOfLastWord(string s) {
int n = s.size();
int result =0, flag = 1;
for(int i=n-1; i>=0; i--){
if(s[i]!=' '){
result++;
flag = 0;
}
if(s[i]==' ' and flag == 0){
return result;
}
}
return result;
}
};
from typing import *
class Solution:
def lengthOfLastWord(self, s: str) -> int:
n = len(s)
result = 0
flag = True
for i in range(n - 1, -1, -1):
if s[i] != ' ':
result += 1
flag = False
if s[i] == ' ' and not flag:
return result
return result
Time Complexity
- The time complexity of the
lengthOfLastWordfunction is \( O(n) \), where \( n \) is the length of the input string. - The algorithm processes each character of the string exactly once, resulting in a linear time complexity.
Space Complexity
- The space complexity of the
lengthOfLastWordfunction is \( O(1) \). - This is because the function uses a constant amount of extra space regardless of the size of the input string.
Approach 02:
-
C++
-
Python
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
using namespace std;
class Solution {
public:
int lengthOfLastWord(string s) {
stringstream ss(s);
string word;
string result;
// Split the string into words using a stringstream
while (ss >> word) {
result = word;
}
// Return the length of the last word
return result.length();
}
};
from typing import *
class Solution:
def lengthOfLastWord(self, s: str) -> int:
data = s.split(" ")
result = ''
for word in data:
if word != "":
result = word
return len(result)
Time Complexity
- The time complexity of the
lengthOfLastWordfunction is \( O(n) \), where \( n \) is the length of the input string. - The algorithm processes each character of the string exactly once, resulting in a linear time complexity.
Space Complexity
- The space complexity of the
lengthOfLastWordfunction is \( O(n) \). - This is because the function uses additional space to store the words and the result string.