LeetCode-----第五十八题-----最后一个单词的长度

本文介绍了一个简单的编程问题,即如何找到给定字符串中最后一个单词的长度。通过去除字符串尾部的空格并从后向前遍历,直到遇到第一个空格或字符串开头,可以有效地解决这个问题。文章提供了一个C++实现的示例。

最后一个单词的长度

难度:简单

给定一个仅包含大小写字母和空格 ' ' 的字符串 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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值