您的位置:首页 > 其它

Leetcode 58. Length of Last Word

2018-01-02 15:05 417 查看
题目的意思是给定一个字符串,字符串由很多单词构成,每个单词之间用空格作为分隔符,要求返回最后一个单词的长度。
 
方法1:先把字符串最后面的空格全部去掉,然后返回最后一个单词的长度。
class Solution {
public:
int lengthOfLastWord(string s) {
int count=0;
int i=s.length()-1,j;
while(s[i]==' ')
i--;
for(j=i; j>=0; --j)
{
if(s[j]==' ')
break;
}
return i-j;
}
};

方法2:用了ss.
class Solution {
public:
int lengthOfLastWord(string s) {
stringstream ss(s);
string temp;
while(ss>>temp);
return temp.size();
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode