# 58. Length of Last Word

Given a string `s` consisting of words and 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.
``````

Constraints:

• `1 <= s.length <= 10^4`
• `s` consists of only English letters and spaces `' '`.
• There will be at least one word in `s`.

``````class Solution {
public:
int lengthOfLastWord(string s) {
int left = 0, right = (int)s.size() - 1, res = 0;
while (s[left] == ' ') ++left;
while (s[right] == ' ') --right;
for (int i = left; i <= right; ++i) {
if (s[i] == ' ') res = 0;
else ++res;
}
return res;
}
};
``````

``````class Solution {
public:
int lengthOfLastWord(string s) {
int res = 0;
for (int i = 0; i < s.size(); ++i) {
if (s[i] != ' ') {
if (i != 0 && s[i - 1] == ' ') res = 1;
else ++res;
}
}
return res;
}
};
``````

``````class Solution {
public:
int lengthOfLastWord(string s) {
int right = s.size() - 1, res = 0;
while (right >= 0 && s[right] == ' ') --right;
while (right >= 0 && s[right] != ' ' ) {
--right;
++res;
}
return res;
}
};
``````

Github 同步地址：

https://github.com/grandyang/leetcode/issues/58

https://leetcode.com/problems/length-of-last-word/

https://leetcode.com/problems/length-of-last-word/discuss/21927/My-3-line-0-ms-java-solution

https://leetcode.com/problems/length-of-last-word/discuss/21892/7-lines-4ms-C%2B%2B-Solution

LeetCode All in One 题目讲解汇总(持续更新中…)

（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，快快加入吧～）

|

Venmo 打赏

—|—

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation