给定一个仅包含大小写字母和空格 ' '
的字符串,返回其最后一个单词的长度。
如果不存在最后一个单词,请返回 0 。
说明:一个单词是指由字母组成,但不包含任何空格的字符串。
示例:
输入: "Hello World" 输出: 5
这道题主要就是注意一下string类型的字符串最后会有一个宫空格,只需要将空格那一位去掉就ok,下面给出AC代码:
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
int lengthOfLastWord(string s) {
int tail=s.size()-1,length=0;
while(tail>=0&&s[tail]==' ')
tail--;
while(tail>=0&&s[tail]!=' '){
if((s[tail]>='a'&&s[tail]<='z')||(s[tail]>='A'&&s[tail]<='Z')){
length+=1;
tail--;
}
else
tail--;
}
return length;
}
int main(){
string s;
cin>>s;
cout<<lengthOfLastWord(s);
return 0;
}