LeetCode 58. 最后一个单词的长度 Length of Last Word(C语言)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hang404/article/details/85260343

题目描述:

给定一个仅包含大小写字母和空格 ’ ’ 的字符串,返回其最后一个单词的长度。
如果不存在最后一个单词,请返回 0 。
说明:一个单词是指由字母组成,但不包含任何空格的字符串。

示例:

输入: “Hello World”
输出: 5

题目解答:

方法1:遍历

遍历的过程中,记录上一个单词的长度。
运行时间0ms,代码如下。

int lengthOfLastWord(char* s) {
    int len = 0, temp = 0;
    while(*s) {
        if(*s == ' ') {
            if(temp != 0)
                len = temp;
            temp = 0;
        }
        else
            temp++;
        s++;
    }
    return temp == 0 ? len : temp;
}

猜你喜欢

转载自blog.csdn.net/hang404/article/details/85260343