题意:
按照以下格式翻转字符串:
方法一:
stringstream类
思路:stringstream类 将字符串以空格分隔得到单词。
再将单词逆序输出。
class Solution {
public:
string ReverseSentence(string str) {
if(str=="")
return str;
stringstream ss(str);//stringstream类
string x,res="";
stack<string> st;//栈实现逆序
while(ss >> x){
st.push(x);//入栈
}
res+=st.top();
st.pop();
while(!st.empty()){//出栈并拼接
res+=" "+st.top();
st.pop();
}
return res;
}
};
时间复杂度:
空间复杂度:![]()
方法二:
模拟
思路:直接遍历字符串模拟。
遍历字符串,如果遇到空格,则入栈;
否则,累加字符串。
class Solution {
public:
string ReverseSentence(string str) {
if(str=="")
return str;
str+=" ";
int len=str.size();
string x="",res="";
stack<string> st;//栈实现逆序
for(int i=0;i<len;i++){
if(str[i]==' '){//如果等于空格
st.push(x);//入栈
x="";
}else{
x+=str[i];
}
}
res+=st.top();
st.pop();
while(!st.empty()){//出栈并拼接
res+=" "+st.top();
st.pop();
}
return res;
}
};
时间复杂度:
空间复杂度:![]()



京公网安备 11010502036488号