Posted on

Description

Submission

class Solution {
public:
    int lengthOfLastWord(string s) {
        int count = 0;
        
        int last = s.size() - 1;
        for(; last >= 0 && s[last] == ' '; last--);
        if(last < 0) return 0;
        for(int i = last; i >= 0; --i) {
            if(s[i] == ' ') break;
            count++;
        }
        return count;
    }
};

There are 2 special cases, one is “” and another is ” ” or “a “.

Leave a Reply

Your email address will not be published. Required fields are marked *