凌云的博客

成功=工作+游戏+少说空话

LeetCode 算法题 58. Length of Last Word

分类:algorithm| 发布时间:2017-02-24 08:08:00


题目

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。

解法

class Solution {
public:
    int lengthOfLastWord(string s) {
        size_t end = s.find_last_not_of(' ');
        if (end == string::npos) {
            return 0;
        }

        size_t beg = s.find_last_of(' ', end);
        if (beg == string::npos) {
            return end + 1;

        }

        return end - beg;
    }

};