字符流中第一个不重复的字符java实现

来源:互联网 发布:edu.cn域名注册 编辑:程序博客网 时间:2024/06/07 03:30

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

思路:遍历数组,新建一个数组,用于记录每个字符出现的次数以及最先出现的位置。

public class Solution {     int count[]=new int[256];    //Insert one char from stringstream    int index=1;    public void Insert(char ch)    {        if(count[ch]==0){          count[ch]=index++;         }        else{            count[ch]=-1;        }    }  //return the first appearence once char in current stringstream    public char FirstAppearingOnce()    {        int temp=Integer.MAX_VALUE;        char ch='#';        for(int i=0;i<256;i++){            if(count[i]!=0&&count[i]!=-1&&count[i]<temp){                temp=count[i];                ch=(char)i;            }        }        return ch;    }}
原创粉丝点击