面试题:字符流中第一个不重复字符

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

import java.util.*;
public class Solution {
    //Insert one char from stringstream
    HashMap<Character,Integer> map = new HashMap<>();
    ArrayList<Character> list = new ArrayList<>();
    public void Insert(char ch)
    {
        if(map.containsKey(ch)){
            map.put(ch,map.get(ch)+1);
        }else{
            map.put(ch,1);
        }
        list.add(ch);
    }
  //return the first appearence once char in current stringstream
    public char FirstAppearingOnce()
    {
        char c='#';
        for(int i=0;i<list.size();i++){
            if(map.get(list.get(i))==1){
                c = list.get(i);
                break;
            }
        }
        return c;
    }
}

注意:list.size()和map.length()和array.length

遍历list

//方法一:
//超级for循环遍历
for(String attribute : list) {
  System.out.println(attribute);
}
//方法二:
//对于ArrayList来说速度比较快, 用for循环, 以size为条件遍历:
for(int i = 0 ; i < list.size() ; i++) {
  system.out.println(list.get(i));
}

遍历map

 //第一种:普遍使用,二次取值
  System.out.println("通过Map.keySet遍历key和value:");
  for (String key : map.keySet()) {
   System.out.println("key= "+ key + " and value= " + map.get(key));
  }
//第四种
  System.out.println("通过Map.values()遍历所有的value,但不能遍历key");
  for (String v : map.values()) {
   System.out.println("value= " + v);
  }
原文地址:https://www.cnblogs.com/Aaron12/p/9512725.html