1、描述_字符串最后一个单词的长度
给你一个字符串 s,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中最后一个单词的长度。
单词 是指仅由字母组成、不包含任何空格字符的最大子字符串。
示例 1:
输入:s = “Hello World”
输出:5
示例 2:
输入:s = " fly me to the moon "
输出:4
来源:力扣(LeetCode)
链接:
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2、关键字
字符串,最后一个长度
3、思路
从后往前遍历,把这个非空的单词存起来,然后返回它的长度
4、notes
就是存起来这个非空的单词
5、复杂度
时间:O(N)
空间:O(n)
6、code
class Solution {
public:
int lengthOfLastWord(string s) {
int n = s.size();
string res ;
for(int i = n - 1 ; i >= 0; i--){ // 从后往前遍历
if(s[i]!=' '){
res += s[i];
}
else{
if(res.size()>0){
break;
}
else{
continue;
}
}
}
return res.size();
}
};
2、反转字符串中的单词
给你一个字符串 s ,请你反转字符串中 单词 的顺序。
单词 是由非空格字符组成的字符串。s 中使用至少一个空格将字符串中的 单词 分隔开。
返回 单词 顺序颠倒且 单词 之间用单个空格连接的结果字符串。
注意:输入字符串 s中可能会存在前导空格、尾随空格或者单词间的多个空格。返回的结果字符串中,单词间应当仅用单个空格分隔,且不包含任何额外的空格。
示例 1:
输入:s = “the sky is blue”
输出:“blue is sky the”
示例 2:
输入:s = " hello world "
输出:“world hello”
解释:反转后的字符串中不能存在前导空格和尾随空格。
链接
2.6 、code
class Solution {
public:
string reverseWords(string s) {
s += " "; // 保障最后一个单词能被添加到res中,
vector<string>res;
string word = "";
for(auto& t: s) {
if(t != ' ') {
word += t;
} else if(t == ' ' && word.size() != 0) {
res.push_back(word);
word = "";
}
}
reverse(res.begin(), res.end());
string ss = res[0];
for(int i = 1; i < res.size(); i++) {
ss += " " + res[i];
}
return ss;
}
};