[Rainbow] istringstream helps you fly ......


  • 0
    class Solution {
    public:
        int lengthOfLastWord(string s) {
            istringstream buf(s);
            string temp;
            int result=0;
            while(buf>>temp){
                result=temp.size();
            }
            return result;
        }
    };
    

    Also you can use the 4-lines-C++ get it done!

    class Solution {
    public:
        int lengthOfLastWord(string s) {
            int  n=s.size(), k=n-1, result=0;
            while(k>=0 && s[k]==' ') k--;
            while(k>=0 && s[k]!=' ') { k--; result++; }
            return result;
        }
    };

Log in to reply
 

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