您的位置:首页 > 其它

LeetCode::Reverse Words in a String

2014-05-27 09:14 225 查看
#include<iostream>
#include<string>
using namespace std;

class Solution {
public:
void reverseWords(string &s) {
int i, n;
string tmp_s;
int word_Length = 0;
if(s.empty())
return ;
for(i = s.length()-1; i >= 0;)
{
word_Length = 0;
while(s[i] == ' ')
i--;
n = i;
while(s
!= ' ' && n >= 0)
{
word_Length++;
n--;
}
n += 1;
tmp_s += s.substr(n,word_Length);
tmp_s += ' ';
i -= word_Length;
}
cout << "tmp_s.length() = " << tmp_s.length() << endl;
/*去掉尾空格*/
i = tmp_s.length()-1;
while(tmp_s[i] == ' ' && i >= 0)
i--;
cout << "i = " << i << endl;
tmp_s.resize(i+1);
cout << "tmp_s.length() = " << tmp_s.length() << endl;
cout << "tmp_s = " << tmp_s << endl;
<span style="white-space:pre">	</span>s = tmp_s;
//cout << tmp_s.append("space") << endl;
//s = tmp_s.substr(0,tmp_s.length());
}
};

int main()
{
string s;
Solution reverseSolution;
getline(cin,s);
cout << s << endl;
cout << "s.length() = " << s.length() << endl;
reverseSolution.reverseWords(s);
cout << s << endl;
cout << "s.length() = " << s.length() << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: