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

  1. Delete the trailing spaces in the string to avoid rfind() finding the last space at the end.
  2. Find the last space before a word using rfind() function.
  3. Check if pos is not string::npos and pos + 1 is not out of range. If valid, take the substring from pos + 1 to the end of the string.

Complexity

  • Time complexity:
    • O(n²) in the worst case because each erase call inside the loop can shift up to n characters.
    • rfind and substr add additional O(n), but erase dominates.
  • 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();
    }
};