剑指offer 面试题35扩展:删除字符串中所有重复出现的字符 (C++版)

版权声明:原创文章,欢迎转载,转载请注明作者和链接。 https://blog.csdn.net/Mary19920410/article/details/77425053

1、题目描述:

定义一个函数,删除字符串中所有重复出现的字符。例如输入“google”,删除重复的字符之后的结果是“gole”。

2、思路分析:

创建一个bool型数组作为哈希表,数组下标对应字符的ascii码,数组的值表示其下标对应的字符在字符串中是否已经出现过。扫描字符串,未出现过,则保留并将哈希表中对应值设置为已出现过。已出现过,则删除。

删除字符时采用重构字符串的思路(详细请看我的上一篇博客:如何在字符串中删除一个字符)。

3、代码及测试:

#include <iostream>
#include <assert.h>
using namespace std;

//删除字符串中所有重复的字符,例如google,删除重复字符后为gole
char * deleteRepeatedChars(char *pString) {
	if(pString == NULL || strlen(pString) == 1) return pString;
	//设置一个bool型数组来实现哈希表,key为数组下表(对应字符的ascii码),value为数组下标对应的字符是否已经在字符串中出现过
	const int tableSize = 256;
	bool hashTable[ tableSize ];
	memset(hashTable, 0, sizeof(hashTable));

	char *slow = pString;
	char *fast = pString;
	while( *fast != '\0') {
		if( !hashTable[ *fast ]) {
			hashTable[ *fast ] = 1;
			*slow = *fast;
			slow ++;
		}

		fast ++;
	}
	*slow = '\0';

	return pString;
}

void test1() { 
	cout << "*****test1 pString中没有重复字符:*****";
	char text[] = "abcdefg";
	char *pString = text;
	pString = deleteRepeatedChars(pString);
	cout << pString << endl;
}

void test2() { 
	cout << "*****test2 pString中有重复字符:*****";
	char text[] = "aabcdccefgeeh";
	char *pString = text;
	pString = deleteRepeatedChars(pString);
	cout << pString << endl;
}

void test3() {
	cout << "*****test3 pString中只有一个字符:*****";
	char text[] = "a";
	char *pString = text;
	pString = deleteRepeatedChars(pString);
	cout << pString << endl;
}

int main() {

	test1();
	test2();
	test3();
	return 0;
}


猜你喜欢

转载自blog.csdn.net/Mary19920410/article/details/77425053
今日推荐