Length of Last Word
Table of Contents
Intuition
First thing come to mind is to find the last space before a word using the rfind() function and then check if the next position after the space is not out of range. Get pos + 1 as the first index of the last word.
Approach
- Delete the trailing spaces in the string to avoid
rfind()finding the last space at the end. - Find the last space before a word using
rfind()function. - Check if pos is not
string::nposand pos + 1 is not out of range. If valid, take the substring frompos + 1to the end of the string.
Complexity
- Time complexity:
O(n²)in the worst case because eacherasecall inside the loop can shift up toncharacters.rfindandsubstradd additionalO(n), buterasedominates.
- Space complexity:
O(n)due to the substring creation (s.substr(pos + 1)).
Code
class Solution {
public:
int lengthOfLastWord(string s) {
for(int i = s.size() - 1; i >= 0; i--){
if(s[i] == ' ') s.erase(s.begin() + i);
else break;
}
size_t pos = s.rfind(' ');
if(pos != std::string::npos && pos + 1 < s.size()){
s = s.substr(pos+1);
}
return s.size();
}
};