思路:借助Hashmap,key保存字符,value保存位置,若重复出现,位置设置为-1。
//变量定义
public HashMap<Character,Integer> mapForUnrepeatableChar=new HashMap<>();
public int charCounter=0;
//方法定义
//Insert one char from stringstream
public void Insert(char ch)
{
//若map中已经存在这个字符,将位置设置为-1,代表重复字符
if(mapForUnrepeatableChar.containsKey(ch)){
mapForUnrepeatableChar.put(ch,-1);
}
else{
mapForUnrepeatableChar.put(ch,charCounter);
}
charCounter++;
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
char answer='#';
int minIndex=charCounter+1,index=-1;
if(mapForUnrepeatableChar.isEmpty()) return answer;
//从map中寻找index最小的key
Iterator iterator=mapForUnrepeatableChar.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry elem=(Map.Entry)iterator.next();
index=(int)elem.getValue();
if(index!=-1){
if(index<minIndex){
minIndex=index;
answer=(char)elem.getKey();
}
}
}
return answer;
}