记录Leetcod第十天(58. Length of Last Word)+ stringstream

LeetCode题解:字符串最后单词长度
本文详细解析LeetCode题目58.Length of Last Word,提供两种解决方案:使用stringstream和逆向遍历。通过实例说明如何准确获取字符串中最后一个单词的长度。

记录Leetcod第十天(58. Length of Last Word)+ stringstream

1.题目

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.

首先就要吐槽一下这个题目,我一直以为类似“a ”这种以空格结尾的就是没有最后一个单词。。。其实这样的话就是a就是最后一个单词。。。生气!

2.例子

Input: “Hello World”
Output: 5

input:"a "
Output:1

input:" "
Output:0

3.解析

有两种方法,第一种就是用stringstream,第二种就是直接倒着数过去。第二种倒着数过去的话就是要考虑后面结尾是一个空格或者好几个空格的情况。但是都很简单了。

4.代码

第一种用stringstream

class Solution {
public:
    int lengthOfLastWord(string s) { 
        stringstream word(s);
        string lastWord="";
        while(word >> lastWord);//以空格为界,一直把每一个单词赋给lastWord,直到最后一个。       
        return lastWord.size();//返回最后一个单词长度。
    }
};

第二种倒数。

class Solution {
public:
    int lengthOfLastWord(string s) { 
        int wordLength=0;
        int i=s.size()-1;
        while(s[i]==' ') i=i-1;//排除后面有很多空格情况
        while(i>=0 && s[i]!=' ')//倒着数一直到遇见空格
        {
            wordLength=wordLength+1;
            i=i-1;
         }                       
        return wordLength;
    }
};

5.stringstream 学习参考

https://blog.youkuaiyun.com/Sophia1224/article/details/53054698

这个超级全:https://blog.youkuaiyun.com/sunshineacm/article/details/78068987

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值