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

去掉字符串相邻重复单词

2014年01月18日 ⁄ 综合 ⁄ 共 680字 ⁄ 字号 评论关闭
// 空间复杂度O(1),时间复杂度O(n)
void str_unique(char* str, int fs, int fd, int ed)
{
	if (fs> (int)strlen(str)) return;

	// skip extra whitespace
	while(str[fs]==' ')++fs;

	// find word [fs, es], contain ' ' or '\0'  in the end
	int es=fs;
	while(1)
	{
		if(str[es]==' ' || str[es]=='\0') break;
		else ++es;
	}

	// compare
	bool flag = true;
	for (int i = fs; i <= es; ++i)
	{
		if (str[i] != str[fd+i-fs])
		{
			flag = false;
			break;
		}
	}

	// move
	if (!flag || ed==-1) 
	{
		for (int i = fs; i <= es; ++i)
		{
			str[ed+i-fs+1] = str[i];
		}
		fd = ed+1;
		ed = fd+es-fs;
	}

	// next
	fs = es+1;
	str_unique(str, fs, fd, ed);
}

void my_str_unique(char* str)
{
	str_unique(str, 0, 0, -1);// ed=-1,skip the first whitespace in the front of the string
}

int _tmain(int argc, char* argv[])
{

	char str[] = "     hello   hello hello  my   my summer     ";
	my_str_unique(str);
	cout<<str<<endl;
	return 0;
}

抱歉!评论已关闭.