翻转字符串里的单词(C++|栈实现)

#include<iostream>
#include<string>
#include<stack>
using namespace std;

class Solution{
public:
string reverseWords(string s){
int left = 0,right = s.size()-1;
while(left <= right&&s[left]==' ') left++;
while(left<=right&&s[right]==' ') right--;

string word;
stack<string> sta;

while(left <= right)
{
char c = s[left];
if(c!=' ')
{
word += c;
}
else if(word.size()&&c==' ')
{
sta.push(word);
word = "";
}
left ++;
}
sta.push(word);
string ans;
while(!sta.empty())
{
ans += sta.top();
sta.pop();
if(!sta.empty()) ans += ' ';
}
return ans;
}
};

原文地址:https://www.cnblogs.com/shiheyuanfang/p/13974768.html