剑指offer------字符流中第一个不重复的字符(java版)

来源:互联网 发布:复制文件 linux 编辑:程序博客网 时间:2024/06/18 17:14

一 题目

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


二 例子

输入'g',输出'g'

输入‘go’,输出'gg'

输入'goo',输出'ggg'

输入'goog',输出'ggg#'


三 思路

因为一个字符不会超过8位,所以创建一个大小为256的整形数组,创建一个List,存放只出现一次的字符。insert时先对该字符所在数组位置数量+1,再判断该位置的值是否为1,如果为1,就添加到List中,不为1,则表示该字符已出现不止1次,然后从List中移除,取出时先判断List的size是否为0,不为0直接List.get(0),就可以得到结果,否则返回‘#’


四 程序源码

import java.util.ArrayList;import java.util.List;public class Solution {   int []countArr = new int[128];        List<Character> charList = new ArrayList<Character>();        //Insert one char from stringstream        public void Insert(char ch){            countArr[ch] ++;            if (countArr[ch] == 1) {                charList.add(ch);            } else {                charList.remove((Character)ch);            }        }        //return the first appearence once char in current stringstream        public char FirstAppearingOnce(){            if (charList.size() == 0) {                return '#';            } else {                return charList.get(0);            }        }}



1 0
原创粉丝点击