字符串反转的艺术:牛客网13278题深度解析

问题描述
题目要求将一个英文句子中的单词顺序反转,同时保持每个单词内部的字符顺序不变。例如: 输入:"hello world" 输出:"world hello"
完整C++解决方案
#include <iostream>
#include <vector>
#include <sstream>
#include <algorithm>
using namespace std;
string reverseSentence(string s) {
// 去除首尾空格
s.erase(0, s.find_first_not_of(" "));
s.erase(s.find_last_not_of(" ") + 1);
// 使用字符串流分割单词
vector<string> words;
stringstream ss(s);
string word;
while (ss >> word) {
words.push_back(word);
}
// 反转单词顺序
reverse(words.begin(), words.end());
// 重新组合句子
string result;
for (int i = 0; i < words.size(); ++i) {
if (i != 0) result += " ";
result += words[i];
}
return result;
}
int main() {
string line;
while (getline(cin, line)) {
cout << reverseSentence(line) << endl;
}
return 0;
}关键技术点解析
常见错误及调试技巧
扩展练习建议
实现原地反转算法(不额外使用存储空间)
处理包含标点符号的句子
尝试不使用STL算法实现相同功能
原创内容 转载请注明出处
