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

来源:互联网 发布:mac清理微信缓存 编辑:程序博客网 时间:2024/06/05 09:05

题目:

在字符串中找出第一个只出现一次的字符。

边界条件及异常:
字符串为空,没有只出现一次的字符。

思路:

可以用hash表来存储出现的字符,然后记录出现的次数,然后按顺序查找第一个次数为1的字符,输出即可。

时间复杂度:O(n)

空间复杂度:O(n)

当然总共有256个字符,所以可以定义大小为256的字符数组,这样空间复杂度为O(1)。

#include <iostream>    #include <vector> #include <queue>#include <string>    #include <stack>    #include <algorithm>  #include <hash_set>  //for hashtable#include <hash_map>#include <unordered_map>#include <set>#include <ctime>using namespace std;char firstAppearOneTime(string str){if (str.size() == 0) return '\0';vector<int> hash(256,0);char *index = &str[0];while (*index != '\0'){hash[*index]++;index++;}index = &str[0];while (*index != '\0'){if (hash[*index] == 1) return *index;index++;}return '\0';}int main(){cout << firstAppearOneTime("abcacbd") << endl;return 0;}


0 0
原创粉丝点击