Skip to content

[LeetCode] 58. 最后一个单词的长度 #90

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Animenzzzz opened this issue Sep 14, 2019 · 0 comments
Open

[LeetCode] 58. 最后一个单词的长度 #90

Animenzzzz opened this issue Sep 14, 2019 · 0 comments

Comments

@Animenzzzz
Copy link
Owner

题目描述:

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

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

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

示例:

输入: "Hello World"
输出: 5

解题思路:这题简单的tag竟然提交了8次。。。这题只要关系非空格就行了,因为有些testcast:a b 中间会有很多空格的情况。使用一个tmp中间值进行记录,每次记录非空格的次数。

C++解题:

class Solution {
public:
    int lengthOfLastWord(string s) {
        if(s.size() == 0) return 0;
        int res = 0;
        for (int i = 0; i < s.size(); i++)
        {
            int tmp = 0;
            while(i < s.size() && s[i] != ' '){
                tmp++;i++;
            }
            if(tmp) res = tmp;
        }
        return res;
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant