Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
#### seems like my code currently couldn't handle the " " case.....hmmm....
#include <string>
#include <iostream>
using namespace std;
// Let's first assume that there is no extra space.
void reverseWord(string& s, int i, int j) {
while(i < j) {
swap(s[i], s[j]);
i++;
j--;
}
}
// secondly, we can add extra space before or after.
void removeSpaces(string& s) {
int i = 0, j = 0, spaceCount = 0;
while(i < s.size()) {
if(s[i] == ' ') {
i++;
spaceCount++;
} else {
if(spaceCount >= 1) {
s[j++] = ' ';
spaceCount = 0;
}
s[j++] = s[i++];
}
}
s[j] = '\0';
if(s[0] == ' ') s = s.substr(1, j - 1);
}
void reverseWords(string& s) {
if(s.size() <= 1) return;
removeSpaces(s);
reverseWord(s, 0, s.size() - 1);
// we then reverse the word one by one.
int i = 0, j = 0;
while(j <= s.size()) {
if(s[j] != ' ' && s[j] != '\0') {
j++;
} else {
reverseWord(s, i, j - 1);
j++;
i = j;
}
}
}
int main(void) {
string words = " abc dc";
removeSpaces(words);
reverseWords(words);
cout << words << endl;
}

本文详细介绍了如何使用C++实现输入字符串的高效单词级反转功能,包括去除多余空格、处理特殊字符等关键步骤,并通过实例代码演示了整个过程。
565

被折叠的 条评论
为什么被折叠?



