Two C++ solutions


  • 0
    Z

    The first one starts from the beginning. reset the counter every time when find a space

    class Solution {
    public:
        int lengthOfLastWord(string s) {
            int length = 0, last=0;
    
            for(char c:s){
                if(c == ' ') {
                	last = length>0?length:last; 
                	length = 0; 
                	continue;
                }
                else length++;
            }
            return length==0?last:length;
        }
    };
    

    The second one starts from then end. It find the space by find_last_of(), and subtracts the string by two indices.

    class Solution {
    public:
        int lengthOfLastWord(string s) {
            int n = s.length();
            int end;
            int space = n;
            while(space){
                end = space;
                space = s.find_last_of(' ', end-1);
                if(space == string::npos) return end;
                else if(end - space > 1) return end - space - 1;
            }
            return 0;
            
        }
    };
    
    

Log in to reply
 

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