字符串
这里用HashMap来实现,当然用ASCII码为键值快点,但用HashMap可以让我们更好的掌握Java的HashMap(其实差不多快);
HashMap<Character, Integer> map = new HashMap<>();
for key in Str
if !map.containKey(key)
map.put(key, 1);
else
map.put(key, map.get(key)++);
for key in Str
if map.get(key)==1
return map.get
字符流
区别在于字符流无法像字符串一样按顺序遍历了,字符是一个接着一个从字符流中读出来,无法用有限的数组存下来。所以只能改用HashMap存下一个index,不再存出现的次数。最后选出最小index;
HashMap<Character, Integer> map = new HashMap<>();
int index = 1;
public void Insert(char ch){
if(!map.containsKey(ch))
map.put(ch,index++);
else
map.put(ch, -1);
}
public char FirstAppearingOnce(){
char ch = '#';
int minIndex = Integer.MAX_VALUE;
for(char Char : map.keySet()){
if(map.get(Char)>0 && map.get(Char)<minIndex){
ch = Char;
minIndex = map.get(Char);
}
}
return ch;
}