【leetcode】Length of Last Word

来源:互联网 发布:编程日志怎么写 编辑:程序博客网 时间:2024/06/15 05:27

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

思路:
从前向后扫描,扫描到空格,视为一个单词,用j记录单词的长度,但是需要注意“a b ”的情况,因此用wordlength来记录前一个单词的长度,来避免这种情况。

class Solution {public:    int lengthOfLastWord(string s) {        if(sizeof(s)==0) return 0;        int i=0,j=0        int wordlength=0;        while(s[i]!='\0')        {            if(s[i]!=' ')            {                i++;                j++;                wordlength=j;            }            else            {                j=0;                i++;            }        }        return max(wordlength,0);    }};

网上看到的答案是从后面往前扫,这个会更快一些

class Solution {public:    int lengthOfLastWord(const char *s) {        int len=strlen(s);        int sum=0;        while(s[len-1]==' ') len--;        for(int i=len-1;i>=0;i--)        {            if(s[i]!=' ')   sum++;            else break;        }        return sum;    }};
0 0