LeetCode 58. 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.

例子:

Input: "Hello World"
Output: 5

分析:
    题意:给定一个字符串s,只包含大小写字母表和空格。返回最后一个单词字符串的长度。
    思路:我们对字符串进行逆序遍历,显然需要找到最后一个单词之前的空格。假设字符串总长度为n,我们用flag表示是否出现字母,则分为4种情况讨论:① s[i] == ' '、flag == false,说明还没有遇到字母,跳过;② s[i] == ' '、flag == true,说明找到了最后的单词、且遇到了空格,结束搜索,跳出;③ s[i] != ' '、flag == false,说明遇到了最后单词的第一个字母,但是搜索还没结束,答案加一,且flag置为true;④ s[i] != ' '、flag == true,说明遇到了最后单词中间的字母,但是搜索还没结束,答案加一。
    最后返回答案。时间复杂度为O(n)。

代码:

#include <bits/stdc++.h>

using namespace std;

class Solution {
public:
    int lengthOfLastWord(string s) {
		int n = s.length();
		// Exceptional Case: 
		if(n == 0){
			return 0;
		}
		bool flag = false;
		int ans = 0;
        for(int i = n - 1; i >= 0; i--){
			if(s[i] == ' ' && !flag){
				continue;
			}
			else if(s[i] == ' ' && flag){
				break;
			}
			else if(s[i] != ' ' && !flag){
				flag = true;
				ans++;
			}
			else if(s[i] != ' ' && flag){
				ans++;
			}
		}
		return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值