首页 > 代码库 > [LeetCode] Length of Last Word

[LeetCode] 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.

For example, 
Given s = "Hello World",
return 5.

 

这题看似很简单,本来想睡前切一道怡情,结果切到一点钟,东改西改还是没AC....

因为edge case 很多,考虑一不周全就是错的,比如 "", " ", " a", " a", "a     b     " 这几个case。

最后我AC的思路是用 i 来记录当前的词长,如果遇到空格则说明此词完毕,把 j = i; i = 0 然后继续直到串尾巴‘\0‘

最后判断 i 是否为0,如果是则返回j,否则返回i

 1 int lengthOfLastWord(const char *s) { 2     int i=0, j=0; 3     while (*s != \0) { 4         if (*s ==  ) { 5             if (i != 0){ 6                 j = i; 7                 i = 0; 8             } 9         }10         else {11             i++;12         }13         s++;14     }15     if (i == 0 ) return j;16     return i;17 }

 

[LeetCode] Length of Last Word