题目:
在字符串中找出第一个只出现一次的字符。如输入“abaccdeff”,则输出'b';
方法一:
方法分析:从头开始扫描字符,如果从头到尾(除了自己以外)没有遇到相同的字符,则返回自己,否则,进行下一个字符的扫描,如果没有只出现一次的字符或者输入的字符串为空则返回' ';
源代码如下:
/*
在字符串中找出第一个只出现一次的字符。如输入“abaccdeff”,则输出'b';
*/
#include<iostream>
#include<vector>
#include<string>
using namespace std;
char Function(string str)
{
if (str.empty())
return ' ';
int len = str.length();
bool flag = false;
for (int i = 0; i < len; ++i)//从前往后,将该位置的元素依次同其他文职上的元素作比较
{
flag = false;
for (int j = 0; j < len; ++j)
{
if (i == j)//如果位置相同,则直接略过
{
continue;
}
if (str[i] == str[j])//如果该元素有重复则将flag置为true;
{
flag = true;
break;
}
}
if (!flag)
return str[i];
}
return ' ';//将前边n-1个元素都有重复,则返回最后一个元素的值
}
int main()
{
string str = "abaccdeff";
cout << Function(str) << endl;
string str2 = "aabbccddeef";
cout << Function(str2) << endl;
string str3;
cout << Function(str3) << endl;
string str4 = "aabbccdd";
cout << Function(str4) << endl;
system("pause");
return 0;
}
运行结果:
b
f
请按任意键继续. . .
方法二:
利用hash_table(不是C++11中标准的函数);
源代码如下:
#include<iostream>
#include<hash_map>
#include<string>
using namespace std;
char Function2(string str)
{
if (str.empty())
return ' ';
int len = str.length();
hash_map<char, int> mhashMap;
for (int i = 0; i < len; ++i)
mhashMap[str[i]]++;
for (const auto &t : mhashMap)
{
if (t.second == 1)
return t.first;
}
return ' ';
}
int main()
{
string str = "abaccdeff";
cout << Function2(str) << endl;
string str2 = "aabbccddeef";
cout << Function2(str2) << endl;
string str3;
cout << Function2(str3) << endl;
string str4 = "aabbccdd";
cout << Function2(str4) << endl;
system("pause");
return 0;
}
运行结果:
b
f
请按任意键继续. . .
方法三:
源代码如下:
#include<iostream>
using namespace std;
char FirstNotRepeatingChar(char *str)
{
if (str == nullptr)
return ' ';
const int tableSize = 256;
unsigned int hashTable[tableSize] = { 0 };
char *pHashKey = str;
while (*(pHashKey) != '\0')
hashTable[*(pHashKey++)]++;
pHashKey = str;
while (*pHashKey != '\0')
{
if (hashTable[*pHashKey] == 1)
return *pHashKey;
else
pHashKey++;
}
return '\0';
}
int main()
{
char str[] = "abaccdeff";
cout << FirstNotRepeatingChar(str) << endl;
char str2[] = "aabbccddeef";
cout << FirstNotRepeatingChar(str2) << endl;
char str3[] = "";
cout << FirstNotRepeatingChar(str3) << endl;
char str4[] = "aabbccdd";
cout << FirstNotRepeatingChar(str4) << endl;
system("pause");
return 0;
}
运行结果如下:
b
f
请按任意键继续. . .