zoukankan      html  css  js  c++  java
  • 剑指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/

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

  • 相关阅读:
    java 虚拟机启动参数[转]
    Android SDK Manager 无法下载更新,或者更新速度超慢,或者待安装包列表不显示
    fluentnhibernet auto mapping
    取消sqlserver 锁表
    TFS 2010 配置的时候,提示TF255466错误
    doc中文乱码的解决方法 中英文切换
    silverlight 读取wcf服务 读取宿主端的config 良好的方法
    dojo+js+html5学习网址
    win 7 64位 配置silverlight 32位的应用程序(sl网站)
    HTTP协议及其POST与GET操作差异 & C#中如何使用POST、GET等
  • 原文地址:https://www.cnblogs.com/master-image/p/3871916.html
Copyright © 2011-2022 走看看