转载并参考July的博客http://topic.csdn.net/u/20101126/10/b4f12a00-6280-492f-b785-cb6835a63dc9.html,万分感谢!
题目:
在一个字符串中找到第一个只出现一次的字符。如输入abaccdeff,则输出b。
解一:
利用栈保存外循环出现的字符,然后进行内循环遍历。如果发现有重复的字符,则出栈,同时推出内循环。再取外循环下一个字符压栈,再进行内循环遍历。如果内循环到结尾,栈中仍不为空,则此时栈中值即为所求。
/*Title: 17.查找第一个只出现一次的字符
Author: gocode
Date: 2012-10-17*/
#include <iostream>
#include <vector>
using namespace std;
char FindFirstChar(char a[])
{
int length = strlen(a);
vector<char> stack;
int j = 0;
for(int i = 0; i < length; ++i)
{
stack.push_back(a[i]);
for(j = 0; j < length; ++j)
{
if(a[j] == stack.back() && i != j)
{
stack.pop_back(); // 此时发生重复字符,所以出栈
break;
}
}
if(j == length && !stack.empty()) // 内循环遍历到尾部,此时没有出栈,则栈中值为第一次出现的字符
break;
}
return stack.empty()? 'n': stack.back();
}
void main()
{
char* myArray = {"abcdabcdeff"};
cout<<"The first appearing char is: "<<FindFirstChar(myArray)<<endl;
system("pause");
}
解二:
统计每个字符出现的次数,保存至另一个数组。然后遍历该数组,查找第一个值为1的,则此值即为所求。
/*Title: 17.查找第一个只出现一次的字符:解二
Author: gocode
Date: 2012-10-17*/
#include <iostream>
#include <string>
using namespace std;
char solve(const string& s)
{
static int times[26] = {0};
memset(times, 0, sizeof (times));
for (size_t i = 0; i < s.size(); ++i)
{
++times[s[i] - 'a'];
}
for (size_t i = 0; i < s.size(); ++i)
{
if (times[s[i] - 'a'] == 1)
{
return s[i];
}
}
return 0;
}
int main()
{
string s = "abaccdeff";
cout << solve(s) << endl;
system("pause");
return 0;
}