[Java-剑指offer] 54.字符流中第一个不重复的字符

mac2024-05-17  35

思路:用HashMap键值对的特性记录字符出现的次数

ArrayList按照HashMap顺序存放所有在 HashMap的值,最后用for循环遍历取出来

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

 

最新回复(0)