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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014067137/article/details/81914146
package arraydemo;

import java.util.ArrayList;
import java.util.HashMap;

/** 
 * @author wyl
 * @time 2018年8月21日下午8:20:05
 * 字符流中第一个不重复的字符
 * 
 * 使用一个HashMap来统计字符出现的次数,同时用一个ArrayList来记录输入流,
 * 每次返回第一个出现一次的字符都是在这个ArrayList(输入流)中的字符作为key去map中查找。
 */
public class Solution8 {
	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);
	}
	
	public char FirstAppearingOnce(){
		char c='#';
		for(char e:list){
			if (map.get(e)==1) {  //说明e是第一次出现,停止查找
				c=e;
				break;
			}
		}
		return c;
	}
}

猜你喜欢

转载自blog.csdn.net/u014067137/article/details/81914146