</>Ali · LeetCode
#0058·EasyStrings

Length of Last Word

LeetCode #58 · Easy · Strings · C++ solution with worked-out approach and complexity analysis.

Approach

String trimming and substring extraction

Strategy

  1. 1Trim trailing spaces from the end
  2. 2Trim leading spaces from the beginning
  3. 3Find the last space in the trimmed string
  4. 4Extract the substring after the last space (or entire string if no
  5. 5Return the length of this substring
Time
O(n)
n is the length of the string
Space
O(n)
the substring creation
Problem description(from LeetCode)

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.

Examples

Example 1
Input:
s = "Hello World"
Output:
5
Note:
The last word is "World" with length 5. Input: s = " fly me to the moon " Output: 4 Explanation: The last word is "moon" with length 4. Input: s = "luffy is still joyboy" Output: 6 Explanation: The last word is "joyboy" with length 6.

Constraints

  • 1 <= s.length <= 10^4
  • s consists of only English letters and spaces ' '.
  • There will be at least one word in s.

C++ Solution

solution.cpp
class Solution {
public:
int lengthOfLastWord(string s) {
    s.erase(s.find_last_not_of(' ') + 1);
    s.erase(0, s.find_first_not_of(' '));
    size_t pos = s.find_last_of(' ');
    string last = pos != string::npos ? s.substr(pos + 1) : s;
    return last.length();
  }
};