- since we only care about the length of the last word of the string, we can start from the back of the string and interate inward
- constraints of the input being only alphabetical and spaces makes the problem somewhat trivial
- the only edge case that really needs to be covered is if the end of the string has spaces before the word is encountered
π€What Did I Struggle With?
~
π‘ Explanation of Solution
~ same as intuition
β Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
π» Implementation of Solution
class Solution {public: int lengthOfLastWord(string s) { int len = 0, tail = s.length() - 1; while (tail >= 0 && s[tail] == ' ') tail--; while (tail >= 0 && s[tail] != ' ') { len++; tail--; } return len; }};