原题链接:
https://leetcode.cn/problems/reverse-words-in-a-string/
问题:
以输入s = " hello world "为例,输出总是" worldld hello"
对比自己的代码与代码随想录上给出的发现是去除多余空格函数中缺少了一个s.resize(slow);
我的代码如下:
// 去除多余的空格
void removeExtraSpaces(string& s) {
int slow = 0;
for (int fast = 0; fast < s.size(); fast++) {
if (s[fast] != ' ') {
if (slow != 0) {
s[slow++] = ' ';
}
while (fast < s.size() && s[fast] != ' ') {
s[slow++] = s[fast++];
}
}
}
}
在for循环后加入s.resize(slow);,输出正确。
解释:
如果不对s进行resize,在执行完毕后,s='hello worldld'
因此反转后会变为" worldld hello"。