您的位置:首页 > 其它

leetcode 之 Length of Last Word

2015-06-05 17:31 405 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: