首页 > 学院 > 开发设计 > 正文

字符流中第一个不重复的字符

2019-11-08 03:07:37
字体:
来源:转载
供稿:网友

题目描述

请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符”go”时,第一个只出现一次的字符是”g”。当从该字符流中读出前六个字符“google”时,第一个只出现一次的字符是”l”。

输出描述:

如果当前字符流没有存在出现一次的字符,返回#字符。

算法描述: 我们只考虑英文字符(ascii),里边只有0-255个字符,所以我们可以建立一个int[] charTable = new int[255],如果是第一次扫描到该字符,则在数组中将对应的位置上记录下字符出现的顺序,如果是第二次出现该字符,则将该字符设为-1,这样当字符流结束的时候,选取出出现位置最早的一个字符。

代码如下:

int[] charTable = new int[255]; int index = 1; //Insert one char from stringstream public void Insert(char ch) { if (charTable[ch] == 0){ charTable[ch] = index; }else{ charTable[ch] = -1; } index ++; } //return the first appearence once char in current stringstream public char FirstAppearingOnce() { char ch = '#'; int minPos = -1; for (int i = 0; i < charTable.length; i++) { if (charTable[i] > 0){ if (minPos == -1){ minPos = i; }else if (charTable[i] < charTable[minPos]){ minPos = i; } } } if (minPos != -1){ return (char) minPos; }else{ return ch; } }
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表