Easy 7 line and Explained , without builtin java function, O(k), k = length of last work, Runtime = 0ms


  • 0
    M
    int last = 0, len = s.length(); 
            while(len > 0 && s.charAt(len-1) == ' ') --len;
            for(int i = len-1; i >= 0; i--) {
                if(s.charAt(i) == ' ') return last;
                last++;
            }
            return last;
    

    skip all the spaces at last using while loop.
    then start the loop from first valid character, if we got a space return
    else it is the first word return the at the end


Log in to reply
 

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