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.

例子

Given s = "Hello World",
return 5.

分析

從后往前遍歷,略過末尾的空格,遇到一個空格字符計數(shù)器加一,直到遇到空格結(jié)束遍歷。

要點(diǎn)

從后往前遍歷

時間復(fù)雜度

O(n)

空間復(fù)雜度

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;
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容