【 关关的刷题日记48】Leetcode 58. Length of Last Word

时间:2022-05-08
本文章向大家介绍【 关关的刷题日记48】Leetcode 58. Length of Last Word,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

关关的刷题日记48 – 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.

For example, Given s = "Hello World", return 5.

题目的意思是给定一个字符串,字符串由很多单词构成,每个单词之间用空格作为分隔符,要求返回最后一个单词的长度。

方法1:先把字符串最后面的空格全部去掉,然后返回最后一个单词的长度。

class Solution {
public:
    int lengthOfLastWord(string s) {
        int count=0;
        int i=s.length()-1,j;
        while(s[i]==' ')
            i--;
        for(j=i; j>=0; --j)
        {
            if(s[j]==' ')
             break;           
        }
        return i-j;
    }
};

方法2:用getline函数,以空格为分隔符,直接读取一个个单词,不过注意”hello World ”这种情况,需要返回最后一个单词World的长度。

class Solution {
public:
    int lengthOfLastWord(string s) {
        stringstream ss(s);
        string temp;
        int length=0;
        while(getline(ss, temp, ' '))
        { 
            if(!temp.empty())
                length=temp.size();
        }
        return length;
    }
}; 

人生易老,唯有陪伴最长情,加油!

以上就是关关关于这道题的总结经验,希望大家能够理解,有什么问题可以在我们的专知公众号平台上交流或者加我们的QQ专知-人工智能交流群 426491390,也可以加入专知——Leetcode刷题交流群(请先加微信小助手weixinhao: Rancho_Fang)。