// Leecode反转字符串问题,先用istringstream将字符串提取出来,然后加上空格,放到string里面
// 有点类似将ip地址以.的形式间隔提取出来,放在vector中进行分析
class Solution {
public:
// 1. 对于空格的处理,还有缺陷,并且复杂度方面较差
// 2. 对于istringstream is(s)什么时候结合getline的‘.’做,什么时候直接is >> temp,还没弄清楚
// string reverseWords(string s) {
// if (s.size() == 0) return s;
// istringstream is(s);
// string st;
// vector<string> vec;
// while(is >> st) {
// vec.push_back(st);
// }
// reverse(vec.begin(), vec.end());
// string res;
// for (int i = 0; i < vec.size() - 1; i++) {
// res += vec[i] + " ";
// }
// res += vec[vec.size() - 1];
// return res;
// }
string reverseWords(string s) {
stack<string> st;
istringstream is(s);
string temp;
string res;
while(is >> temp) {
st.push(temp);
st.push(" ");
}
if (!st.empty()) st.pop();
while (!st.empty()) {
res += st.top();
st.pop();
}
return res;
}
};
京公网安备 11010502036488号