LeetCode(59)Length of Last Word

本文介绍了一个简单的C++程序,该程序用于计算给定字符串中最后一个单词的长度。文章详细解释了如何处理各种特殊情况,例如空字符串、只包含一个单词的字符串以及字符串末尾存在多个空格的情况。

题目

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.

分析

题目要求得出所给字符串最后一个单词的长度。
这其实是一个很简单的题目,主要有几个需要注意的点:

  • 空字符串,自然是返回0
  • 只有一个单词的字符串,返回长度即可
  • 若是输入字符串为“hello “也就是说,最后是多个空字符时,返回的长度要求是最后非空字符组成的最后一个单词而不是0;

AC代码

class Solution {
public:
    int lengthOfLastWord(string s) {
        int len = strlen(s.c_str());

        //如果是空字符串或者是单字符,则直接返回长度
        if (len == 0)
            return len;


        int i = len-1 , j = 0;
        //从后向前找到非空字符
        while (i>=0 && s[i] == ' ')
            --i;

        for (j = i; j>=0 && s[j] != ' '; --j)
            ;

        return i - j;
    }
};

GitHub测试程序源码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值