小小程序媛  
得之坦然,失之淡然,顺其自然,争其必然

题目

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测试程序源码

posted on 2015-08-15 21:08  Coding菌  阅读(112)  评论(0编辑  收藏  举报