解题思路
1、利用一个额外的数组把每一个单词截下来,再倒叙保存结果
2、不使用额外空间的解法:
- 去除字符串中多余的空格
- 翻转整个字符串
- 翻转单个字符串
去除字符串中多余的空格,不调用系统自带的erase函数,因为时间开销比较多,自己写一个双指针的方法
代码:使用额外空间ac100%
class Solution {
public:
string reverseWords(string s) {
int n = s.size();
vector<string> s_nums;//存储划分出来的字符串
string temp;//临时存储每一个单词
for(int i = 0;i < n;i++) {
if(s[i] == ' ') {
if(temp.size() != 0)s_nums.push_back(temp);
temp.clear();//每一次保存结果之后要清空临时数组
}
else {
temp.push_back(s[i]);
if(i == n - 1)s_nums.push_back(temp);//防止最后一个字符不是空格
}
}
string ans;
//倒叙输出结果
for(int i = s_nums.size()-1;i > 0;i--) {
ans += s_nums[i];
ans.push_back(' ');
}
ans += s_nums[0];//避免最后一个单词后面加上空格
return ans;
}
};
代码:不使用额外空间ac100%
class Solution {
public:
//去除多余的空格
void easreExtraSpaces(string& s) {
int n = s.size();
int slow_index = 0, fast_index = 0;
//去除前置空格
while (s[fast_index] == ' ' && fast_index < n) {
fast_index++;
}
//去除中间空格
for (; fast_index < n; fast_index++) {
if (fast_index - 1 > 0 && s[fast_index] == ' ' && s[fast_index - 1] == ' ') {
continue;
}
else {
s[slow_index++] = s[fast_index];
}
}
//去除最后的空格
if (s[slow_index - 1] == ' ')slow_index--;
s.resize(slow_index);
}
string reverseWords(string s) {
//去除多余的空格
easreExtraSpaces(s);
int n = s.size();
//整体翻转
reverse(s.begin(), s.end());
//单个字符串翻转
for (int i = 0, j = 0; j < n; j++) {
if (s[j] == ' ' || j == n-1) {
int k = j == n - 1 ? j : j - 1;
while (i < k) {
swap(s[i], s[k]);
i++;
k--;
}
i = j + 1;
}
}
return s;
}
};