#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] != ' ' && 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;
}
LeetCode::Reverse Words in a String
最新推荐文章于 2018-07-18 08:25:00 发布