Jack Li's Blog

58. Length of Last Word

class Solution {
public:
    int lengthOfLastWord(string s) {
        int n = s.size();
        int l = n-1;
        int r = l;

        while(r >= 0 && s[r] == ' ') r--;
        l = r;
        while(l >= 0 && s[l] != ' ') l--;
        
        return r - l;
    }
};