// 面试题50(二):字符流中第一个只出现一次的字符
// 题目:请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从
// 字符流中只读出前两个字符"go"时,第一个只出现一次的字符是'g'。当从该字
// 符流中读出前六个字符"google"时,第一个只出现一次的字符是'l'。 #include <iostream>
#include <limits> using namespace std; class CharStatistics
{
public:
CharStatistics() : index()//后初始化index=0
{
for (int i = ; i < ; ++i)
occurrence[i] = -;
} void Insert(char ch)
{
if (occurrence[ch] == -)//之前没有过,插入index
occurrence[ch] = index;
else if (occurrence[ch] >= )//之前出现过,设为-2
occurrence[ch] = -; index++;//用来指示出现过一次的字符的顺序
} char FirstAppearingOnce()
{
char ch = '\0';
int minIndex = numeric_limits<int>::max();//类型int的最大值
for (int i = ; i < ; ++i)
{
if (occurrence[i] >= && occurrence[i] < minIndex)//对只出现一次的字符进行搜索,找到最先出现的那个值
{
ch = (char)i;
minIndex = occurrence[i];
}
} return ch;
} private:
// occurrence[i]: A character with ASCII value i;
// occurrence[i] = -1: The character has not found;
// occurrence[i] = -2: The character has been found for mutlple times
// occurrence[i] >= 0: The character has been found only once
int occurrence[];
int index;
}; // ====================测试代码====================
void Test(const char* testName, CharStatistics chars, char expected)
{
if (testName != nullptr)
printf("%s begins: ", testName); if (chars.FirstAppearingOnce() == expected)
printf("Passed.\n");
else
printf("FAILED.\n");
} int main()
{
CharStatistics chars; Test("Test1", chars, '\0'); chars.Insert('g');
Test("Test2", chars, 'g'); chars.Insert('o');
Test("Test3", chars, 'g'); chars.Insert('o');
Test("Test4", chars, 'g'); chars.Insert('g');
Test("Test5", chars, '\0'); chars.Insert('l');
Test("Test6", chars, 'l'); chars.Insert('e');
Test("Test7", chars, 'l');
system("pause");
return ;
}

最新文章

  1. JS-自制提速小工具:开发页面时需要按比例计算宽高值的快速计算器
  2. Javascript函数节流
  3. spring笔记2 spring MVC的基础知识2
  4. [ASE]Sprint1总结 &amp; Sprint2计划
  5. Servlet基础(下)
  6. 软件工程随堂小作业—— 寻找“水王”(C++)
  7. spring TaskExecutor
  8. [Guava官方文档翻译] 1.Guava简介 (Introduction)
  9. Unity3D脚本--真实1
  10. HDU 3639 Hawk-and-Chicken(Tarjan缩点+反向DFS)
  11. vim列编辑
  12. 反编译看java for-each循环
  13. POJ 1971 Parallelogram Counting (Hash)
  14. 弹性布局(Flex布局)整理
  15. MyBatis——MyEclipse中使用mybatis-generator
  16. 微信服务号获取openid方法
  17. Subversion客户端接受服务器证书出现“The certificate hostname does not match”的问题
  18. selector的例子
  19. C#:VS2010 由于缺少调试目标&quot;xx.exe&quot;,Visual Studio无法开始调试,请生成项目并重试,或者相应地设置OutputPath和AssemblyName属性,使其指向目标程序集的正确位置
  20. c++ Arx二次开发创建椭圆和样条曲线

热门文章

  1. SpringMVC之数据绑定
  2. An Example of How Oracle Works
  3. c++ STL中的set和multiset
  4. 初识wxPython
  5. Solr基本操作
  6. hibernate 和mybatis
  7. 11.2.0.4 sql*loader/oci direct load导致kpodplck wait before retrying ORA-54
  8. RSD 直观介绍
  9. Delphi XE5 for Android (十一)
  10. 图片处理工具类 util