Simple solution with one loop.


  • 0

    I noticed that some detailed solution (the one not calling library function) will have two loops.

    class Solution {
    public:
    int lengthOfLastWord(string s) {
        int r=s.length();
        int l=r-1;
        while(l>=0){
            if(s[l]==' '&& r-l==1){
                --l; --r;
            }
            else if(s[l]!=' ')
                --l;
            else
                break;
        }
        return r-l-1;
    }};

Log in to reply
 

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