58. Length of Last Word leetcode solution in c++

int lengthOfLastWord(string s) {
    int length = 0;
    int i = s.size() - 1;

    while (i >= 0 && s[i] == ' ') {
        i--;
    }

    while (i >= 0 && s[i] != ' ') {
        length++;
        i--;
    }

    return length;
}

Explanation:

  1. We start by initializing the length variable to 0. This variable will store the length of the last word in the given string s.
  2. We initialize i to s.size() - 1, which is the last index of the string s.
  3. We enter a while loop that checks two conditions: i should be greater than or equal to 0, and the character at index i in the string s should be a space ' '. This loop helps us skip any trailing spaces at the end of the string.
  4. Inside the loop, we decrement i by 1 to move to the previous character.
  5. After the loop ends, we have skipped all the trailing spaces at the end of the string.
  6. We enter another while loop that checks two conditions: i should be greater than or equal to 0, and the character at index i in the string s should not be a space ' '. This loop helps us count the length of the last word.
  7. Inside the loop, we increment the length variable by 1 to count the current character.
  8. We decrement i by 1 to move to the previous character.
  9. After the loop ends, we have counted the length of the last word in the string.
  10. We return the length variable as the result.

This solution iterates through the string s from the end, skipping any trailing spaces and counting the length of the last word. It has a time complexity of O(n), where n is the length of the string s.