(LeetCode每日一刷14)最后一个单词的长度

题目描述:

给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。

如果不存在最后一个单词,请返回 0 。

说明:一个单词是指由字母组成,但不包含任何空格的字符串。

示例:

输入: "Hello World"
输出: 5

我提交的代码:

class Solution {
public:
    int lengthOfLastWord(string s)
    {
        decltype (s.size()) i;
        int temp_len = 0;
        int result_len = 0;
        for (i = 0; i < s.size(); ++i)
        {
            if(s[i] != ' ')
            {
                temp_len++;
            }
            else
            {
                if (temp_len != 0)
                {
                    result_len = temp_len;
                }
                temp_len = 0;
            }
        }
        
        if (temp_len != 0)
        {  
            result_len = temp_len;
        }
        
        return result_len;
        
    }
};

猜你喜欢

转载自blog.csdn.net/songsong2017/article/details/84401926