LeetCode题解——最后一个单词的长度
- 题目介绍
- 解题思路
这题中心思想就是找到字符串最后一个从不为空字符开始到为空字符开始的子字符串,c++里面有多种思路可以解决,下面举2种常见的,易于思考到的
第一种,用c++的find函数,从字符串的末尾开始find,首先找到第一个不为空字符的index,然后从这个index开始找到第一个为空字符的位置,这个位置距离就是字符串长度
第二种,用迭代器从字符串后面开始遍历,记录从第一个不为空到为空的距离,其实find内部也是用的遍历
- 代码示例
方法一:
class Solution {
public:
int lengthOfLastWord(string s) {
int index1 = s.find_last_not_of(' ',string::npos);
if(index1 < 0) {
return 0;
}
int index2 = s.find_last_of(' ',index1);
return index1-index2;
}
};
方法二:
class Solution {
public:
int lengthOfLastWord(string s) {
string::reverse_iterator it;
int count = 0;
for(it = s.rbegin();it != s.rend();it++) {
while(*it != ' ' && it != s.rend()) {
count++;
it++;
}
if(count != 0) {
break;
}
}
return count;
}
};