My c solution recording traverse state.

  • 0
    int lengthOfLastWord(string s) {
            int ans=-1, state=0;//state---0 means out of a word.
            for(int i=0; i<s.size(); ++i){
                if( (s[i]>='a' && s[i]<='z') || (s[i]>='A' && s[i]<='Z')){
                    if(state==0)  { ans=1; state=1;}
                    else ans++;
            return ans==-1?0:ans;

Log in to reply

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