[leetcode] 18. Length of Last Word

时间:2023-03-09 08:00:30
[leetcode] 18. Length of Last Word

这个题目很简单,给一个字符串,然后返回最后一个单词的长度就行。题目如下:

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.

我的思路就是先把字符串反转,然后找到第一个' '后弹出,这个需要注意的大概就是很可能最后不是字符,而是一个标点,所以要判断一下。题解如下:

class Solution {
public:
int lengthOfLastWord(const char *s)
{
string tmp = s;
reverse(tmp.begin(), tmp.end()); int sum, i, len;
sum = i = 0;
len = tmp.length();
while (i < len)
{
if (isalpha(tmp[i]))
{
sum++;
i++;
break;
}
else
{
i++;
}
} while (tmp[i] != ' ' && i < len)
{
sum++;
i++;
} return sum;
}
};

如上,不难。