您的位置:首页 > 其它

Leetcode - string - Reverse Words in a String

2014-04-20 21:49 246 查看
class Solution {
public:
void reverseWords(string &s) {
istringstream record(s);
string temp;
vector<string> vec;
while(record>>temp)
{
vec.push_back(temp);
}
int theSize=vec.size();
s="";
for(auto i=theSize-1;i>=0;i--)
{
s=s+vec[i];
if(i!=0)
s=s+" ";
}
}
};


不使用vector,直接使用istringstream来解决

/**
* 1.s is empty.
* 2.s is spaces.
* 3.s ends or begins with spaces.
*/
class Solution {
public:
void reverseWords(string &s) {
if(s.empty())
return;
istringstream record(s);
string str;
s.clear();
while(record>>str)
{
s=str+' '+s;
}
if(!s.empty())
s.erase(s.end()-1);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: