[leetcode-58]Length of Last Word(c)

来源:互联网 发布:淘宝流量互刷 编辑:程序博客网 时间:2024/04/28 19:19

问题描述:
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.

分析:这道题很简单,只要从后向前,将空格过滤掉,然后如果没有了,直接返回0,然后再从后向前查找,当出现空格时,退出。返回计数。

代码如下:0ms

int lengthOfLastWord(char* s) {    int length = strlen(s);    int index = length-1;    while(index>=0&&s[index]==' ')        index--;    if(index<0)        return 0;    int count = 0;    while(index>=0&&s[index]!=' ')    {        count++;        index--;    }    return count;}
0 0
原创粉丝点击