题解 | #翻转单词序列#
翻转单词序列
https://www.nowcoder.com/practice/3194a4f4cf814f63919d0790578d51f3
class Solution { public: std::string ReverseSentence(std::string str) { // 找到两个空格之间 或两侧的单词,将内容压入堆栈,然后弹出回原位 if(str.empty()) return str; std::stringstream ss(str); std::string word; std::stack<std::string> stack; std::string resultStr; while(std::getline(ss, word, ' ')){ stack.push(word); } while (!stack.empty()) { resultStr += stack.top(); stack.pop(); resultStr += ' '; } resultStr.pop_back(); return resultStr; } };