LeetCode : Lendth of Last Word
这道题非常简单,需要考虑的细节也很少,在这个基础上,我们需要考虑的是怎么将代码的运行效率写得比较高。
形如: “hello ” 返回的是5
代码如下(leetCode 测得运行时间为0ms):
int lengthOfLastWord(char *s)
{
int wordLen = 0;
int tmp = 0; //!< 中间变量
char *str = s;
if (s == NULL) //!< 每次解引用之前,都应该判断是否为空
{
printf("The string is NULL!\n");
return 0;
}
while (*str != '\0')
{
tmp = (*str == ' ') ? 0 : ++tmp; //!< 不为空格则加1
wordLen = (tmp == 0) ? wordLen : tmp; //!< worldLen 保存最新的非0值
++str;
}
return wordLen;
}