题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
输出描述:
如果当前字符流没有存在出现一次的字符,返回#字符。
思路:用map来统计字符出现的次数,用list来记录字符
代码:
package com.example.shirodemo; import java.util.*; /** * Created by ASUS on 2018/7/2 * * @Authod Grey Wolf */ public class Practice { // 记录当前字符出现的次数 private Map<Character,Integer> map = new HashMap(); // 记录字符 private List<Character> list = new ArrayList(); public static void main(String[] args) { Practice practice=new Practice(); practice.insert('g'); practice.insert('o'); System.out.println(practice.firstAppearingOnce()); } //Insert one char from stringstream public void insert(char ch) { // 将字符记录下来 list.add(ch); // 将字符出现次数记录下来 if(map.get(ch) != null){ map.put(ch,map.get(ch) + 1); }else{ map.put(ch,1); } } //return the first appearence once char in current stringstream public char firstAppearingOnce() { if(list.size() == 0){ return '#'; } for(Character ch : list){ if(map.get(ch) == 1){ return ch; } } return '#'; } }
效果:
g
我的座右铭:不会,我可以学;落后,我可以追赶;跌倒,我可以站起来;我一定行。