DIY -- 4 lines, use methods of std::string -- 2 lines, C++


  • 0
    Q
    class Solution {
    public:
        int lengthOfLastWord(string s) {
            /// DIY
            /*char *q, *p=&s[s.size()-1], *pend=&s[-1];
            for(;p!=pend && *p==' ';--p) {}
            for(q=p;p!=pend && *p!=' ';--p) {}
            return q-p;*/
            /// use methods of std::string
            int x;
            return ((x=s.find_last_not_of(' '))==std::string::npos)? 0 :x-s.find_last_of(' ',x);
        }
    };

Log in to reply
 

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