第一个只出现一次的字符

来自:剑指offer


分析:通过两次遍历字符串计算得到,第一次遍历字符串通过一个数组确定每个字符出现的次数,第二次遍历字符串确定第一个只出现一次字符是谁。时间复杂度为O(n)。

  1. #include "stdafx.h"  
  2. #include <iostream>  
  3. using namespace std;  
  4.   
  5. char FirstNotRepeatingChar(const char* pString)  
  6. {  
  7.     if ( pString == NULL )  
  8.         return '\0';  
  9.   
  10.     unsigned int hashTable[256];  
  11.     memset(hashTable, 0, sizeof(unsigned int)*256);  
  12.   
  13.     const char* pStart = pString;  
  14.     while ( *pStart != '\0' )  
  15.         hashTable[*(pStart++)]++;  
  16.   
  17.     pStart = pString;  
  18.     while ( *pStart != '\0' )  
  19.     {  
  20.         if( hashTable[(*pStart)] == 1 )  
  21.             break;  
  22.         else  
  23.             pStart++;  
  24.     }  
  25.       
  26.     if ( *pStart != '\0' )  
  27.         return *pStart;  
  28.     else  
  29.         return '\0';  
  30. }  
  31.   
  32. int _tmain(int argc, _TCHAR* argv[])  
  33. {  
  34.     char* p = "abaccdefdef";  
  35.     cout << FirstNotRepeatingChar(p) <<endl;  
  36.   
  37.     system("pause");  
  38.     return 0;  
  39. }  

扩展:

1:实现一函数,给定两个字符串str1和str2,将字符串str2中在str1出现的字符删除掉。例如,str1=“We are strudent”,str2=“eas”,最终返回“W r tudnt”。

做法:遍历str2并将其字符放入哈希数组中,再遍历str1,去掉哈希数组中存在的字符即可。与上题思路一致。时间复杂度为O(n+m),n和m分别为str1和str2的长度。空间为O(1)。

2:实现一函数,将字符串中出现重复字符全部去掉。例如,str=“google”,那么返回为“gole”。

做法:类似,可用一个布尔数组去记录。第一次出现标志位true,当第二次访问该字符时,当前标志位为true时,删除当前字符。时间复杂度为O(n),n为str的长度。空间为O(1)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值