問題
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;
}
};