1.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.
Example:
Input: "Hello World"
Output: 5
2.題目要求:給定一個字符串电媳,然后判斷最后一個單詞的長度。
3.方法:要記錄的是空格前的字符開始索引庆亡,然后遇到空格得出單詞長度匾乓。最后要注意的是,可能整個字符沒有空格又谋,或者最后一個不是空格拼缝,退出循環(huán)時要檢測一下。
4.代碼:
class Solution {
public:
int lengthOfLastWord(string s) {
int len = 0, tail = s.length() - 1;
while (tail >= 0 && s[tail] == ' ') tail--;
while (tail >= 0 && s[tail] != ' ') {
len++;
tail--;
}
return len;
}
};