题目:在一个字符串中找到第一个只出现一次的字符。
如输入abaccdeff,则输出b。
如输入abaccdeff,则输出b。
算法思路:
此算法的实现在于选择适当的数据结构,可以选择一种叫映射表的数据结构
映射表简单地说就是进化的“数组”,但是“数组”的下标可以是任意类型
所以可以选择字符与数字的映射表作为数据结构,然后扫描字符串的每一个字符,如果当前字符还没有在映射表中,则添加进去映射表,并将其值设为1,反之,则将该值对应的值加1
算法的伪代码
create map<char, int>
//scan the string,
for i <- 1 to s.length
if char is already existed in the map
then add its count
else assign 1 to the map
for begin <- m.begin() to m.end()
if found first not repeating char
then return its char
C++实现
//find first char that appear once in the string
char FirstNotRepeatingChar(const string &s)
{
//create map<char, int>
map<char, int> m;
//scan the string
for(int i = 0; i != s.length(); ++i)
{
//if char is already existed in the map
if(m[s[i]])
{
//then add its count
++m[s[i]];
}
else
{
//else assign 1 to the map
m[s[i]] = 1;
}
}
//for begin <- m.begin() to m.end()
for(auto begin = m.begin(); begin != m.end(); ++begin)
{
//if found first not repeating char
if(begin->second == 1)
{
//then return its char
return begin->first;
}
}
}