面试题35:第一个只出现一次的字符

题目:在字符串中找出第一个只出现一次的字符。如“abaccdeff”,则输出‘b'。

解法一:暴力搜索,时间复杂度为O(N2)

解法二:利用hash表,时间复杂度为O(N),空间复杂度为O(N)

 1 char firstNotRepeatChar(string&str)
 2 {
 3     if (str.size()==0)
 4         return '\0';
 5     const int tableSize = 256;
 6     unsigned int hashTable[tableSize];
 7     for (int i = 0; i < tableSize; ++i)
 8         hashTable[i] = 0;
 9     
10     for (int i = 0; i < str.size(); ++i)
11         hashTable[str[i]]++;
12     
13     for (int i = 0; i < str.size(); ++i)
14     {
15         if (hashTable[str[i]] == 1)
16             return str[i];
17     }
18     return '\0';
19 }

 

posted @ 2015-07-08 12:32  Rosanne  阅读(219)  评论(0编辑  收藏  举报