題目鏈接
tag:
- Easy;
question
??Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string.
A word is a maximal substring consisting of non-space characters only.
Example 1:
Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.
Example 2:
Input: s = " fly me to the moon "
Output: 4
Explanation: The last word is "moon" with length 4.
Example 3:
Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.
提示:
- 1 <= s.length <= 104
- s consists of only English letters and spaces ' '.
- There will be at least one word in s.
思路:
??這道題要求我們求字符串最后一個(gè)單詞的長(zhǎng)度斗幼,很簡(jiǎn)單倒序遍歷垢乙,遇到空格跳過(guò)系瓢,直到遇到第一個(gè)字母蟹地,開(kāi)始計(jì)數(shù)逮走,再遇到空格就退出即可,代碼如下:
class Solution {
public:
int lengthOfLastWord(string s) {
if (s.empty()) return 0;
if (s.size() == 1) return 1;
int count = 0;
bool flag = true;
// 從后面開(kāi)始肠阱,遇到空格就跳過(guò),知道遇到第一個(gè)字母朴读,開(kāi)始計(jì)數(shù)屹徘,再遇到空格就break
for (int i = s.size() - 1; i >= 0 ; --i) {
if (s[i] == ' ') {
if (!flag)
break;
}
else {
++count;
flag = false;
}
}
return count;
}
};