class Solution {
public:
void reverseWords(string &s) {
string word;
stack<string> wordsStack;
stringstream ss(s);
while(ss>>word)
{
wordsStack.push(word);
}
string res = "";
bool first = true;
while(!wordsStack.empty())
{
if(!first)
res += " ";
res += wordsStack.top();
wordsStack.pop();
first = false;
}
s = res;
}
};[LeetCode]Reverse Words in a String
最新推荐文章于 2024-01-04 11:20:32 发布
本文介绍了一种使用栈来实现字符串中单词顺序反转的方法。通过istringstream读取单词并压入栈中,再依次弹出形成反转后的字符串。此方法适用于C++环境。
501

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



