题目地址:https://leetcode-cn.com/problems/length-of-last-word/
题目描述:
给定一个仅包含大小写字母和空格 ' '
的字符串,返回其最后一个单词的长度。
如果不存在最后一个单词,请返回 0 。
说明:一个单词是指由字母组成,但不包含任何空格的字符串。
示例:
输入: "Hello World"
输出: 5
class Solution {
public:
int lengthOfLastWord(string s) {
if(s.size()==0)return 0;
s.erase(0, s.find_first_not_of(' '));
s.erase(s.find_last_not_of(' ') + 1);
string delim(" ");
int last = 0;
size_t index = s.find_first_of(delim, last);
while(index != string::npos){
last = index + 1;
index = s.find_first_of(delim, last);
}
return s.size() - last;
}
};
主要用到string中trim和split的用法,详细见:https://blog.csdn.net/z13653662052/article/details/88636999