这道题分步骤来写:
首先要去除多余的空格:有两种方法
第一种:快慢指针法:时间复杂度低但是思路复杂
void removeExtraSpaces(string& s) {
int slowIndex = 0, fastIndex = 0;
while (s.size() > 0 && fastIndex < s.size() && s[fastIndex] == ' ') {
fastIndex++;
}
for (; fastIndex < s.size(); fastIndex++) {
if (fastIndex - 1 > 0 && s[fastIndex - 1] == s[fastIndex] && s[fastIndex] == ' ') {
continue;
} else {
s[slowIndex++] = s[fastIndex];
}
}
if (slowIndex - 1 > 0 && s[slowIndex - 1] == ' ') {
s.resize(slowIndex - 1);
} else {