3ms easy to learn solution


  • 0
    L

    class Solution {
    public:
    int lengthOfLastWord(string s) {
    int i=0,j=-1,k=-1,lastlen=0;
    if(s.size()==0) return 0;
    while(i<s.size()){
    if(s[i]==' '){
    j = i;
    }else{
    k = i;
    lastlen = k-j;
    }
    i++;
    }
    return lastlen;
    }
    };

    // j=most recent ' ' index, k= most recent non-' ' index;
    //iterate to move j and k. each time update k, we also update our result last-length.
    //it is ensured that lastlen is always the length of the last word.


Log in to reply
 

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