Leetcode: Length of Last word

本文介绍了一种使用 C++ 实现计算字符串中最后一个单词长度的方法。通过自动机思想和状态转换,该方法能够有效地处理包含空格的字符串输入,并提供了一个简单的实现示例。

思路:

自动机, 每次输入一个空格, 就进行一次状态转换

逆序遍历的效果应该会更好, 不过我就是简单的正序遍历了下练练自动机

代码:

#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
	int len;
	void countWord(const char *s, int &i, const int &n) {
		len = 0;
		while(s[i] != ' ' && i < n) {
			len++;
			i++;
		}
	}
    int lengthOfLastWord(const char *s) {
        len = 0;
		int size = strlen(s);
		for(int i = 0; i < size; i ++) {
			while(s[i] == ' ')
				i++;
			if(i != size)
				countWord(s, i, size);
		}
		return len;
    }
};

  

转载于:https://www.cnblogs.com/xinsheng/p/3439175.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值