C++, 4ms, just scan from the right end


  • 1
    D

    Scan from the right end to get the end of the last word and the start of the last word

    class Solution {
    public:
        int lengthOfLastWord(string s) {
            int res =0, len=s.size(), i = len-1, end=0;
            while(i>=0 && s[i] == ' ') --i;
            end = i;
            while(i>=0 && s[i] != ' ') --i;
            return end-(i<0?0:i+1)+1;
            
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.