剑指offer 53:字符流中第一个不重复的字符

题目描述

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

输出描述:
如果当前字符流没有存在出现一次的字符,返回#字符。
思路:

  1. 其实和找出第一个不重复的字符一样,只不过一个是在字符流中,没啥区别
  2. 利用值为下标法,计算每个值对应的下标数组计数为多少
  3. 因为是注意int类型的上下限,数组
public class Solution {
    //Insert one char from stringstream
    int count[]=new int[256];
    int index=1;
    public void Insert(char ch)
    {
        if(count[ch]==0){   //如果只出现一次的count为1,多次的为-1
          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;
    }
}
发布了105 篇原创文章 · 获赞 19 · 访问量 4967

猜你喜欢

转载自blog.csdn.net/jiohfgj/article/details/105044461