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

//思路一:暴力解法
//先将所有数据插入,再进行统计

private StringBuffer buffer=new StringBuffer();
//Insert one char from stringstream
public void Insert(char ch)
{
    buffer.append(ch);
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce(){
    int[] freq = new int[256];

    for(int i=0;i<buffer.length();i++){
        char ch = buffer.charAt(i);
        freq[ch]++;
    }

    for(int i=0;i<buffer.length();i++){
        char ch = buffer.charAt(i);
        if(freq[ch]==1){
            return ch;
        }
    }
    return '#';
}
//思路二:
//利用队列先进先出的特性

//统计字符出现的次数
private int[] freq = new int[256];
//队列中值存储出现一次的字符,并且出队顺序就是入队顺序一致
private Queue<Character> queue = new LinkedList<>();
//Insert one char from stringstream
public void Insert(char ch) {
    freq[ch]++;
    queue.offer(ch);
    while (!queue.isEmpty() && freq[queue.peek()]>1){
        queue.poll();
    }
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce(){
    return queue.isEmpty()? '#':queue.peek();
}

https://www.mianshi.onlinehttps://www.i9code.cn

本文由博客一文多发平台 OpenWrite 发布!

逃跑的眼镜_bvbEK5
7 声望0 粉丝