letecode [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.

题目大意:

  给定一个仅包含大小写字母和空格的字符串,输出最后一个单词的长度

理解:

  从后往前遍历字符串,遇到第一个单词后的空格即停止,输出这个单词的长度。

  需要注意的是,末尾可能有多个空格,应先过滤掉这些空格,再计算单词的长度。

代码C++:

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

运行结果:

  执行用时 : 4 ms  内存消耗 : 8.8 MB

posted @ 2019-06-04 10:59  lpomeloz  阅读(132)  评论(0编辑  收藏  举报