跳转至

58.Length of Last Word

Tags: Easy String

Links: https://leetcode.com/problems/length-of-last-word/


Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string.

If the last word does not exist, return 0.

Note: A word is defined as a maximal substring consisting of non-space characters only.

Example:

Input: "Hello World"
Output: 5

class Solution {
public:
    int lengthOfLastWord(string s) {
        std::ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        cout.tie(NULL);

        int n = s.size();
        if (!n) return 0;
        //处理掉空格
        int pos = n - 1;
        while (pos >= 0 && s[pos] == ' ') --pos;

        int res = 0;
        for (int i = pos; i >= 0; --i) {
            ++res;
            if (s[i] == ' ') {
                --res;
                break;
            }
        }
        return res;
    }
};