难度:简单
给定一个仅包含大小写字母和空格 ' ' 的字符串 s,返回其最后一个单词的长度。如果字符串从左向右滚动显示,那么最后一个单词就是最后出现的单词。
如果不存在最后一个单词,请返回 0 。
说明:一个单词是指仅由字母组成、不包含任何空格字符的 最大子字符串。
示例:
输入: "Hello World"
输出: 5
题目解析:
简单题,最需要注意的地方是这个字符串最后有空格需要去除
参考代码:
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <deque>
#include <stack>
#include <algorithm>
#include <map>
using namespace std;
class Solution {
public:
int lengthOfLastWord(string s) {
if (s.empty())
return 0;
int index = s.size() - 1;
while (index >= 0 && s[index] == ' ') --index;//去除空格
int res = 0;
while (index >= 0 && s[index] != ' ')//直接从最后开始遍历
{
--index;
res++;
}
return res;
}
};
int main(void)
{
Solution my_class;
string str = "Hello World";
cout << my_class.lengthOfLastWord(str) << endl;
system("pause");
return 0;
}
本文介绍了一个简单的编程问题,即如何找到给定字符串中最后一个单词的长度。通过去除字符串尾部的空格并从后向前遍历,直到遇到第一个空格或字符串开头,可以有效地解决这个问题。文章提供了一个C++实现的示例。
1933

被折叠的 条评论
为什么被折叠?



