记录Leetcod第十天(58. Length of Last Word)+ stringstream
1.题目
Given a string s consists of upper/lower-case alphabets and empty space characters ’ ', return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
首先就要吐槽一下这个题目,我一直以为类似“a ”这种以空格结尾的就是没有最后一个单词。。。其实这样的话就是a就是最后一个单词。。。生气!
2.例子
Input: “Hello World”
Output: 5
input:"a "
Output:1
input:" "
Output:0
3.解析
有两种方法,第一种就是用stringstream,第二种就是直接倒着数过去。第二种倒着数过去的话就是要考虑后面结尾是一个空格或者好几个空格的情况。但是都很简单了。
4.代码
第一种用stringstream
class Solution {
public:
int lengthOfLastWord(string s) {
stringstream word(s);
string lastWord="";
while(word >> lastWord);//以空格为界,一直把每一个单词赋给lastWord,直到最后一个。
return lastWord.size();//返回最后一个单词长度。
}
};
第二种倒数。
class Solution {
public:
int lengthOfLastWord(string s) {
int wordLength=0;
int i=s.size()-1;
while(s[i]==' ') i=i-1;//排除后面有很多空格情况
while(i>=0 && s[i]!=' ')//倒着数一直到遇见空格
{
wordLength=wordLength+1;
i=i-1;
}
return wordLength;
}
};
5.stringstream 学习参考
https://blog.youkuaiyun.com/Sophia1224/article/details/53054698
这个超级全:https://blog.youkuaiyun.com/sunshineacm/article/details/78068987