原文链接:http://blog.csdn.net/zhaojinjia/article/details/11888143
来自:剑指offer
分析:通过两次遍历字符串计算得到,第一次遍历字符串通过一个数组确定每个字符出现的次数,第二次遍历字符串确定第一个只出现一次字符是谁。时间复杂度为O(n)。
- #include "stdafx.h"
- #include <iostream>
- using namespace std;
- char FirstNotRepeatingChar(const char* pString)
- {
- if ( pString == NULL )
- return '\0';
- unsigned int hashTable[256];
- memset(hashTable, 0, sizeof(unsigned int)*256);
- const char* pStart = pString;
- while ( *pStart != '\0' )
- hashTable[*(pStart++)]++;
- pStart = pString;
- while ( *pStart != '\0' )
- {
- if( hashTable[(*pStart)] == 1 )
- break;
- else
- pStart++;
- }
- if ( *pStart != '\0' )
- return *pStart;
- else
- return '\0';
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- char* p = "abaccdefdef";
- cout << FirstNotRepeatingChar(p) <<endl;
- system("pause");
- return 0;
- }
扩展:
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)。