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.

Example:

Input: "Hello World"
Output: 5

 

要完成的函数:

int lengthOfLastWord(string s) 

 

代码:

int lengthOfLastWord(string s) 
{
    if(s.empty())//判断是否为空
    return 0;
    int i,j=0,flag=0;
    for(i=s.size()-1;i>=0;i--)//这道题要求输出最后一个单词的长度,所以从后面开始检索会容易很多
    {
        if(s[i]!=' ')//找到第一个不是空格的字符
        {
            j++;//开始统计
            flag=1;//作为一个标记,已经统计到非空字符
        }
        else if(s[i]==' '&&flag==1)
        break;
    }
    return j;//如果字符串为“    ”,这种情况呢?同样可以处理
}

说明:

字符串只包含大小写字母和空格,各种边界情况要考虑清楚。比如空字符串,比如全为空格的字符串,比如只有一个单词没有空格的字符串,比如在最后的单词后面还有几个空格的字符串。最开始本来想利用空格来断开各个单词,但觉得有点麻烦,不如从后面直接搜索,碰到第一个非空格字符就是了。

写完主体代码,最后把各种可能的边界情况考虑了一下,形成如上最终代码。

这份代码成绩一般,only beats 33.07% of cpp submissions。

原文地址:https://www.cnblogs.com/chenjx85/p/8709785.html