Leetcode

比起POJ弱爆了一题,从后往前扫描一遍,O(n)时间,仅仅要注意各种极端情况就可以,不明确通过率为什么仅仅有13%。


#include<iostream>
#include<string>
using namespace std;


class Solution {
public:
	void reverseWords(string &s) {

		char* cstr = new char[s.size()+1];

		int cc = 0;
		int revstrC = s.size() - 1;

		while (revstrC >= 0)
		{
			while (revstrC>=0 && s.at(revstrC) == ' ')
			{
				revstrC--;
			}

			if (revstrC >= 0)//find the end of a word
			{
				int end = revstrC;

				while (revstrC >= 0 && s.at(revstrC) != ' ')
					revstrC--;

				s.copy(cstr+cc, end-revstrC, revstrC+1);

				cc = cc + end - revstrC;

				cstr[cc] = ' ';

				cc++;
			}
		}
		cstr[cc-1] = '';
		
		s.assign(cstr);
	}
};


int main()
{
	Solution sol;
	string str = "  Hello  fwe  asg   wf      vergv    ";
	sol.reverseWords(str);

	cout << str << endl;
}


原文地址:https://www.cnblogs.com/mfrbuaa/p/3803084.html