题目:查找一个字符串中第一个只出现两次的字符。比如:“abcdefabcdefabc”中第一个只出现两次为‘d’,要求时间复杂度为O(N),空间复杂度为O(1)
思路:
创建一个辅助数组(大小为256),数组的下标表示字符的ASCII码,遍历字符串,每出现一个,在对应位置加一,最后遍历数组就可以找到第一个出现两次的字符
代码:
char
find_char_instr(std::string
&str)
{
char
num_of_char[256] = {
'\0'
};
for
(size_t
idx
= 0;
idx
<
str.size();
++idx)
{
num_of_char[str[idx]]++;
}
for
(size_t
idx
= 0;
idx
<
str.size();
++idx)
{
if
(num_of_char[str[idx]]
== 2)
return
str[idx];
}
return
'\0';
}
int
main()
{
std::string str
=
"abdecefabcdfabc";
char
ret
=
find_char_instr(str);
if
(ret
==
'\0')
cout
<<
"没有出现两次的字符。"
<<
endl;
else
cout
<<
"第一个出现两次的字符为 :"
<<
ret
<<
endl;
system("pause");
return
0;
}