58. Length of Last Word

2017-05-10  本文已影响0人  RobotBerry

问题

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.

例子

Given s = "Hello World",
return 5.

分析

从后往前遍历,略过末尾的空格,遇到一个空格字符计数器加一,直到遇到空格结束遍历。

要点

从后往前遍历

时间复杂度

O(n)

空间复杂度

O(1)

代码

class Solution {
public:
    int lengthOfLastWord(string s) {
        if (s.empty()) return 0;
        
        int len = 0;
        bool lastWord = false;
        for (int i = s.size() - 1; i >= 0; i--) {
            if (!lastWord && s[i] == ' ') continue;
            if (lastWord && s[i] == ' ') break;
            lastWord = true;
            len++;
        }
        return len;
    }
};
上一篇下一篇

猜你喜欢

热点阅读