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

来源:互联网 发布:chocobank网络剧照片 编辑:程序博客网 时间:2024/06/07 08:50

题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符”go”时,第一个只出现一次的字符是”g”。当从该字符流中读出前六个字符“google”时,第一个只出现一次的字符是”l”。
输出描述
如果当前字符流没有存在出现一次的字符,返回#字符。

解题思路
1.对每一个插入的字符,统计其出现的次数,不妨使用整型的count[char]表示;
2.按照插入的顺序,读出第一个出现次数为1的字符。

代码如下:

package firstAppearingOnce;public class Solution {    String str = "";    int[] count = new int[256];    public static void main(String[] args) {        Solution s = new Solution();        s.Insert('g');        s.Insert('o');        s.Insert('o');        s.Insert('g');        s.Insert('l');        s.Insert('e');        System.out.println(s.FirstAppearingOnce());    }    //Insert one char from stringstream    public void Insert(char ch)    {        str+=ch;        count[ch]++;    }    //return the first appearence once char in current stringstream    public char FirstAppearingOnce()    {        for(int i = 0; i<str.length(); i++){            char ch = str.charAt(i);            if(count[ch] == 1)                return ch;        }        return '#';    }}

运行结果:
l
注:来自剑指offer刷提整理,代码可直接运行。