现在的位置: 首页 > 综合 > 正文

Leetcode – Reverse Words

2019年04月17日 ⁄ 综合 ⁄ 共 577字 ⁄ 字号 评论关闭

比起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] = '\0';
		
		s.assign(cstr);
	}
};


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

	cout << str << endl;
}
【上篇】
【下篇】

抱歉!评论已关闭.