63.在字符串中删除特定的字符(字符串)。
题目:输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。例如,输入”They are students.”和”aeiou”,
则删除之后的第一个字符串变成”Thy r stdnts.”。
分析:这是一道微软面试题。在微软的常见面试题中,与字符串相关的题目占了很大的一部分,
因为写程序操作字符串能很好的反映我们的编程基本功。思路:
老题了。首先要考虑的是怎么快速的删除节点。我觉的只要是考虑到要快速插入删除的,就用链表。然后就是要考虑怎么快速的判断在第二个字符串中是否存在当前的字符。这点如果用扫描的的话,整个的时间复杂度就是O(mn)。那么我们就想到可以使用hash表的方式,就可以在O(1)的时间复杂度中判断是否存在。整个的时间复杂度为O(m+n)
贴上代码,代码不是我自己写的,是在网上搜集的:
///// Delete all characters in pStrDelete from pStrSource///void DeleteChars(char* pStrSource, const char* pStrDelete){ if(NULL == pStrSource || NULL == pStrDelete) return; // Initialize an array, the index in this array is ASCII value. // All entries in the array, whose index is ASCII value of a // character in the pStrDelete, will be set as 1. // Otherwise, they will be set as 0. const unsigned int nTableSize = 256; int hashTable[nTableSize]; memset(hashTable, 0, sizeof(hashTable)); const char* pTemp = pStrDelete; while ('\0' != *pTemp) { hashTable[*pTemp] = 1; ++ pTemp; } char* pSlow = pStrSource; char* pFast = pStrSource; while ('\0' != *pFast) { // if the character is in pStrDelete, move both pStart and // pEnd forward, and copy pEnd to pStart. // Otherwise, move only pEnd forward, and the character // pointed by pEnd is deleted if(1 != hashTable[*pFast]) { *pSlow = *pFast; ++ pSlow; } ++pFast; } *pSlow = '\0';}