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;
}
};