Fork me on GitHub

leetcode之58. 最后一个单词的长度

题目描述:

给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。

如果不存在最后一个单词,请返回 0 。

说明:一个单词是指由字母组成,但不包含任何空格的字符串。

示例:

1
2
3
> 输入: "Hello World"
> 输出: 5
>

解题思路:

思路一:

时间复杂度: $O(n)​$, 空间复杂度: $O(1)​$.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int lengthOfLastWord(string s) {
int count = 0;
int flag = 1;
for(int i = s.length()-1; i>=0; i--)
{
if(s[i] != ' ')
{
count++;
flag = 0;
}
else
{
if(flag == 0)
break;
}
}
return count;
}
};

思路二:

用字符流stringstream,

时间复杂度: $O(n)$, 空间复杂度: $O(n)$.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int lengthOfLastWord(string s) {
stringstream ss(s);
string t = "";
int result = 0;
while(ss >> t)
{
result = t.length();

}
return result;
}
};