Length of Last Word

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:

1
2
3
Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.

Example 2:

1
2
3
Input: s = "   fly me   to   the moon  "
Output: 4
Explanation: The last word is "moon" with length 4.

Example 3:

1
2
3
Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.

个人解答:

时间复杂度:O(n)

空间复杂度:O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
int lengthOfLastWord(string s) {
int s_size = s.size();
int count = 0;
for (int i = s_size; i >= 0; --i) {
if (isalpha(s[i]))
count++;
else {
if (count > 0)
return count;
}
}
return count;//单词前不存在空格的情况
}