剑指offer课外两道习题解法
1、定义一个函数,删除字符串中所有重复出现的字符,例如输入“google”,删除重复的字符之后的结果为“gole”。
解题思路:像这种求字符串的重复字符,并且去掉重复字符,我们一般可以用哈希表来解决,时间复杂度一般为o(n),后面我将列举三个非常明显的例子用哈希表来解决。
首先上段代码:void pSizePath(const char* inputStr,char* outputStr),其中inputStr为输入的字符串,outputStr为删除重复字符之后的字符串。
void pSizePath(const char* inputStr,char* outputStr)
{
const unsigned int number=256;
unsigned int hashTable[number];
const char* hashKey=inputStr;
for (unsigned int i = 0; i < number; i++)
{
hashTable[i]=0; //初始化哈希表
}
while (*hashKey!='\0')
{
hashTable[*hashKey]++; //表中出现的次数
hashKey++;
}
hashKey=inputStr; //重新遍历一遍
while (*hashKey!='\0')
{
if (hashTable[*hashKey]==1) //只出现一次就保存一次
{
*(outputStr++)=*hashKey;
}
else if (hashTable[*hashKey]>1) //出现两次就保存刚出现的第一次
{
*(outputStr++)=*hashKey;
hashTable[*hashKey]=0; //这里设置为0,以后都不会判断这个字符了。
}
hashKey++;
}
*outputStr='\0'; //字符串结束标志
}
2、定义一个函数,输入两个字符串,从第一个字符串中删除在第二个字符串中出现的所有字符串。例如从第一个字符串“we are students."中删除在第二个字符串串中”aeiou“中出现过的字符得到的结果是”w r Stdents."
解题思路:思路还是和上题一样,用哈希表来解决,只不过是我们保存字符串的时候需要额外一个字符串指针来储存。即快慢指针,这种解决方法非常巧妙。
pSizePath(const char* inputStr1,const char* inputStr2,char* outputStr)函数中inputStr1为哈希表中的key值,inputStr2指向输入的字符串,outputStr指针指向输出字符串。
void pSizePath(const char* inputStr1,const char* inputStr2,char* outputStr)
{
const int number=256;
int hashTable[number];
const char* hashKey=inputStr1;
for (int i = 0; i < number; i++)
{
hashTable[i]=0; //初始化哈希表
}
while (*hashKey!='\0')
{
hashTable[*hashKey]++; //表中出现的次数
hashKey++;
}
char* outputStr1=outputStr;
while (*inputStr2!='\0')
{
if (!(hashTable[*inputStr2]>=1)) //出现大于或等于一次的不显示
{
*(outputStr1++)=*inputStr2;
}
inputStr2++ ;
}
*outputStr1='\0'; //字符串结束标志
}
经过测试可行。
作者:曹麒文
出处:http://www.cnblogs.com/master-image/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面

浙公网安备 33010602011771号