题目:在一个字符串中找到第一个只出现一次的字符。如输入 abaccdeff,则输出 b。
分析:这道题是 2006 年 google 的一道笔试题。
分析:
用 Hash, 时间和空间复杂度是 O(N)
当然,如果字符是 ASCII 编码的话,可以开一个 256长的数组来对每个字符出现的次数进行记录。
下面的代码采用了 unordered_map, 用 HASH 实现。。
有几点注意的地方:
1. unordered_map[key] ,返回一个 reference, 指向键值是 key 的元素。
如果该元素尚未存在,则自动插入这元素,value 值调用默认构造函数。对于那些没有默认构造函数的一定要注意。
// copyright @ L.J.SHOU Mar.10, 2014 // find 1st single number #include <iostream> #include <string> #include <unordered_map> using namespace std; void FirstSingleNumber(const string& str) { if(str.empty()) return; unordered_map<char, int> char_set; for(int i=0; i<str.size(); ++i) ++ char_set[str[i]]; for(int i=0; i<str.size(); ++i) { // char_set[i] will automatically insert i if i not existed // value is set by default constructor if(char_set[str[i]] == 1) { cout << str[i] << endl; return; } } } int main(void) { string str("abaccdeff"); FirstSingleNumber(str); return 0; }
Interview----First single charactor,布布扣,bubuko.com
Interview----First single charactor
原文:http://blog.csdn.net/shoulinjun/article/details/20950713