Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

click to show clarification.

Clarification:

  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.

题目解析:

(1)一开始首先将开头和结尾的空格去掉

(2)将剩余字符串逆转

(3)从头开始寻找将单词进行逆转,并将单词内的多余的空格去掉


#include 
#include 

using namespace std;

void reverseWords(string &s) {
	string::iterator it;

	int len = s.length();

	int begin = 0;
	int end = len-1;

	while(begin <= end && s[begin] == ' ')
	{
		it = s.begin() + begin;
		s.erase(it);
		end--;
	}
	if(s.length() == 0)
	{
		return;
	}

	while(end >=0 && s[end] == ' ')
	{
		it = s.begin() + end;
		s.erase(it);
		end--;
	}
	if(s.length() == 0)
	{
		return;
	}

	begin = 0;
	end = s.length()-1;

	int pBegin = begin;
	int pEnd = end;
	while(pBegin < pEnd)
	{
		char temp = s[pBegin];
		s[pBegin] = s[pEnd];
		s[pEnd] = temp;
		pBegin++;
		pEnd--;
	}

	int pSunEnd = begin;
	int pSunBegin = begin;
	while(pSunEnd <= end)
	{
		while(pSunEnd <= end && s[pSunEnd] != ' ')
			pSunEnd++;

		int tempEnd = pSunEnd-1;

		while(pSunBegin < tempEnd)
		{
			char c = s[pSunBegin];
			s[pSunBegin] = s[tempEnd];
			s[tempEnd] = c;

			pSunBegin++;
			tempEnd--;
		}

		pSunEnd++;
		while(pSunEnd <= end && s[pSunEnd] == ' ')
		{
			it = s.begin() + pSunEnd;
			s.erase(it);
			end--;
		}

		pSunBegin = pSunEnd;
	}
}

int main(void)
{
	string s("   the sky is   blue   ");

	cout << s.c_str() << endl;

	reverseWords(s);

	cout << s.c_str() << endl;
	system("pause");
	return 0;
}


你可能感兴趣的:(LeetCode)