面試OR筆試18——哈希表處理字符串

1哈希表處理字符

字符的哈希表雖然佔用了一定的額外空間,但可以大大地減少時間複雜度,是典型的空間換取時間的栗子。下面的栗子都屬於這一類。

1.1 第一個只出現k次的字符

【題目】

在字符串中找出第一個只出現k次的字符,如字符串abeccdaff第一個只出現1次的字符時e

【代碼】

char firstNRepeatingChar(const char *str, int n = 1){
	if(!str) return '\0';
	const int tableSize = 1<<8;
	unsigned table[tableSize] = {0};
	const char *sp = str;
	while(*sp) ++table[*(sp++)];
	for(sp = str;*sp;++sp) if(table[*sp]==n) return *sp;
	return '0';
}



 

1.2 從字符串中刪除字符

【題目】

求從第一個字符串中刪除在第二個字符串中出現過的所有字符後的字符串,並返回刪除字符的個數。例如:從We are students. 中刪除aoeiu 後的字符串爲W r stdnts. 返回5。

【代碼】

int removeCharsFromString(char *str, const char *s){
	int res(0);
	if(!(str && s)) return res;
	const int tableSize = 1<<8;
	unsigned table[tableSize] = {0};
	while(*s) table[*(s++)] = 1;
	char *sp = str;
	while(*sp){
		if(table[*sp]) ++res;
		else *(str++) = *sp;
		++sp;
	}
	*str = '\0';
	return res;
}



 

1.3 限制字符串中字符最多重複出現的次數(刪除字符串重複字符)

【題目】

限制一個字符串中字符重複出現的次數,特別的,當次數限制爲1時就是刪除字符串中重複出現的字符。返回值要求返回刪除的字符數。例如:aaaabbbccd 次數限制爲1時爲abcd,返回6。

【代碼】 

int removeDuplication(char *str, unsigned n = 1){
	int res(0);
	if(!str) return res;
	const int tableSize = 1<<8;
	unsigned table[tableSize] = {0};
	char *sp = str;
	while(*sp) table[*(sp++)] = n;
	for(sp = str;*sp;++sp){
		if(table[*sp]) {
			--table[*sp];
			*(str++) = *sp;
		}
		else ++res;
	}
	*str = '\0';
	return res;
}



 

1.4 判斷兩個字符串是否爲變位詞

【題目】

在英語中,如果兩個單詞中出現的字母相同,並且每個字母出現的次數也相同,那麼這兩個單詞互爲變位詞。要求判斷給定的兩個字符串是否互爲變位詞。

【代碼】

 

bool isAnagtam(const char *s1, const char *s2){
	if(!s1) return !(s2 && *s2);
	if(!s2) return !(s1 && *s1);
	const int tableSize = 1<<8;
	int table[tableSize] = {0};
	while(*s1) ++table[*(s1++)];
	while(*s2) --table[*(s2--)];
	for(int k1(0);k1<tableSize;++k1)
		if(table[k1]) return false;
	return true;
}


 

 

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