# 最后一个单词的长度
给你一个字符串 s
,由若干单词组成,单词之间用空格隔开。返回字符串中最后一个单词的长度。如果不存在最后一个单词,请返回 0 。
单词 是指仅由字母组成、不包含任何空格字符的最大子字符串。
示例 1:
输入:s = "Hello World"
输出:5
示例 2:
输入:s = " "
输出:0
提示:
1 <= s.length <= 104
s
仅有英文字母和空格 ' '
组成
以下错误的选项是?
## aop
### before
```cpp
#include
using namespace std;
```
### after
```cpp
int main()
{
Solution sol;
string s = "Hello World";
int res;
res = sol.lengthOfLastWord(s);
cout << res;
return 0;
}
```
## 答案
```cpp
class Solution
{
public:
int lengthOfLastWord(string s)
{
if (s.empty())
return 0;
int pos = s.find_last_of(' ');
while (pos == s.length() - 1)
{
if (s.empty())
return 0;
s.erase(pos);
pos = s.find_last_of(' ');
}
return s.length() - pos;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
int lengthOfLastWord(string s)
{
string word;
stringstream ss(s);
while (ss >> word)
{
}
return word.size();
}
};
```
### B
```cpp
class Solution
{
public:
int lengthOfLastWord(string s)
{
int countWord = 0;
for (int index = 0; index < s.size(); index++)
{
if (s[index] == ' ')
{
if (index != s.size() - 1 && s[index + 1] != ' ')
{
countWord = 0;
continue;
}
else
continue;
}
countWord++;
}
return countWord;
}
};
```
### C
```cpp
class Solution
{
public:
int lengthOfLastWord(string s)
{
if (s.empty())
return 0;
vector word;
int begin, lenWord = 0;
for (int i = 0; i < s.size(); i++)
{
if ((i == 0 && s[i] != ' ') || (i != 0 && s[i - 1] == ' ' && s[i] != ' '))
{
begin = i;
lenWord++;
if (i == s.size() - 1)
{
word.push_back(s.substr(begin, lenWord));
break;
}
}
else if (s[i] != ' ' && i != s.size() - 1)
{
lenWord++;
}
else if (i != 0 && s[i - 1] != ' ' && s[i] == ' ')
{
word.push_back(s.substr(begin, lenWord));
lenWord = 0;
}
else if (s[i] != ' ' && i == s.size() - 1)
{
word.push_back(s.substr(begin, lenWord + 1));
}
}
if (word.empty())
return 0;
else
return word[word.size() - 1].size();
}
};
```