C++ solution Easy to understand


  • 1
    S

    class Solution {

    public:

    int lengthOfLastWord(string s) {
        int len=0;
        for (int i=s.length()-1;i>=0;i--){
            if (s[i]!=' '){
                len++;
            }
            if (s[i]==' ' && len!=0) return len;
        }
        return len;
    }
    

    };


  • 0
    S
    class Solution {
    public:
        int lengthOfLastWord(string s) {
            istringstream iss(s);
            vector<string> tokens{istream_iterator<string>{iss},istream_iterator<string>{}};
            return(tokens.size()==0?0:tokens[tokens.size()-1].size());
        }
    };

Log in to reply
 

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