• 剑指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!='')
    	{
    		hashTable[*hashKey]++;   //表中出现的次数
    		hashKey++;
    	}
    	hashKey=inputStr;       //重新遍历一遍
    	while (*hashKey!='')
    	{
    		if (hashTable[*hashKey]==1)   //只出现一次就保存一次
    		{
    			*(outputStr++)=*hashKey;
                    }
    		else if (hashTable[*hashKey]>1)    //出现两次就保存刚出现的第一次
    		{
    			*(outputStr++)=*hashKey;
    			hashTable[*hashKey]=0;   //这里设置为0,以后都不会判断这个字符了。
    		}
    		hashKey++;
    	}
    	*outputStr='';     //字符串结束标志
    }
    

      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!='')
    	{
    		hashTable[*hashKey]++;   //表中出现的次数
    		hashKey++;
    	}
    	char* outputStr1=outputStr;
    	while (*inputStr2!='')
    	{
    		if (!(hashTable[*inputStr2]>=1))   //出现大于或等于一次的不显示
    		{
    			*(outputStr1++)=*inputStr2;
    
    		}
    		inputStr2++ ;
    	}
    	*outputStr1='';     //字符串结束标志
    }
    

      经过测试可行。

    作者:曹麒文

    出处:http://www.cnblogs.com/master-image/

    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面

  • 相关阅读:
    Ubuntu12.04安装svn1.8
    [NOIP模拟测试3] 建造游乐园 题解(欧拉图性质)
    图论模板
    [bzoj3073] Journeys 题解(线段树优化建图)
    [bzoj3033]太鼓达人 题解(搜索)
    [NOIP2016]天天爱跑步 题解(树上差分) (码长短跑的快)
    [HNOI2015]菜肴制作 题解(贪心+拓扑)
    [SDOI2015]排序 题解 (搜索)
    [CQOI2011]放棋子 题解(dp+组合数学)
    [ZJOI2011]看电影(组合数学/打表+高精)
  • 原文地址:https://www.cnblogs.com/master-image/p/3871916.html
Copyright © 2020-2023  润新知