2020-07-03
1.题目描述
输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和
普通字母一样处理。例如输入字符串"I am a student. ",则输出"student. a am I"。
2.题解
将得到的每个字符串放在栈中输出
3.代码
class Solution {
public:
string reverseWords(string s) {
int len=s.size();
if (!len) return "";
stack<string> mystack;
string tmp="";
for (int i=0;i<len;i++){
if (s[i]==' '){
if (tmp!="") mystack.push(tmp);
tmp="";
}else{
tmp+=s[i];
}
}
if (tmp!="") mystack.push(tmp);
string res="";
int l=mystack.size();
for (int i=0;i<l-1;i++){
res+=mystack.top();
mystack.pop();
res+=' ';
}
if (!mystack.empty()){
res+=mystack.top();
mystack.pop();
}
return res;
}
};