2016年2月18日 星期四

LEET code -- Length of Last Word

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.




但是這解法不好
因為strlen本身就會對s 字串跑一次  太浪費


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
int lengthOfLastWord(char* s) {
    int size=strlen(s);
    if(size<=0)return 0;
    int count=0;
    for(int i=size-1;i>=0;i--){
        if(count==0 && s[i]==' ')continue;
        else if(s[i]!=' ')count++;
        else if(s[i]==' ')return count;
    }
    return count;
}

strlen


1
2
3
4
5
6
7
8
9
size_t
strlen(str)
 const char *str;
{
 register const char *s;

 for (s = str; *s; ++s);
 return(s - str);
}

----
跑一次for就好


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
int lengthOfLastWord(char* s) {
    //int size=strlen(s);
    //if(size<=0)return 0;
    int count=0,lastcount=0;
    for(;*s;s++){
        if(count==0 && *s==' ')continue;
        else if(*s!=' ')count++;
        else if(*s==' '){
            lastcount = count;
            count=0;
        }
    }
    return count!=0 ? count:lastcount;
}

沒有留言:

張貼留言