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();
}
};
方法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 - 58. Length of Last Word
- 【leetcode】58. Length of Last Word
- leetcode 58. Length of Last Word
- Leetcode 58. Length of Last Word
- 【一天一道LeetCode】#58. Length of Last Word
- 【LeetCode】58. Length of Last Word
- Leetcode:58. Length of Last Word
- leetcode 58. Length of Last Word
- leetcode-58. Length of Last Word
- leetcode-java-58. Length of Last Word
- LeetCode 58. Length of Last Word
- leetcode -58. Length of Last Word
- LeetCode 58. Length of Last Word
- LeetCode 58. Length of Last Word Java
- Leetcode 58. Length of Last Word
- 【一天一道LeetCode】#58. Length of Last Word
- 【Leetcode】58. Length of Last Word
- LeetCode58. Length of Last Word
- LeetCode 58. Length of Last Word
- leetcode 58. Length of Last Word(easy)