3 line c++ solution using find_last_of

  • 0

    first remove all spaces from end of the string, then find the index of first space from the end

        int lengthOfLastWord(string s) {
            while(s.back()==' ') s.pop_back();
            if (s.size()==0) return 0;
            return s.size() - s.find_last_of(' ', s.size()-1) - 1;

Log in to reply

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