字符串中旋转单词

/*
问题描述:给定一个字符串,单词以空格隔开,对字符串进行转换,例如“I love you”转换成“you love I”,要求空间复杂度为O(1)
来源:网易算法课
日期:2017-10-24
说明:共分为两步,第一步:将整个字符串进行翻转;第二步:对每个单词进行翻转
*/

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

void reverseString(string& str, int begin, int end)
{
	int i = begin, j = end;
	while (i < j)
	{
		char c = str[i];
		str[i] = str[j];
		str[j] = c;
		i++;
		j--;
	}
	//cout << str << endl;
}

void reverseWord(string& str)
{
	reverseString(str, 0, str.length() - 1);
	cout << str << endl;
	int begin = 0, end = begin;

	while (end < str.length())
	{
		while (str[end] != ' ' && end < str.length())
			end++;
		reverseString(str, begin, end - 1);
		begin = end + 1;
		end = begin;

	}

}
/*
int main()
{
	string str = "im love you";
	//reverseString(str, 0, str.length() - 1);
	reverseWord(str);

	cout << str << endl;
	return 0;
}
*/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章