import java.util.HashMap;
public class E50FirstNonredundantChar {
public static String getChar(String str){
if (str == null || str.length() == 0)
return null;
final int SIZE = 256;
HashMap<Character, Integer> hashMap = new HashMap<>(SIZE);
char[] chars = str.toCharArray();
for (int i = 0; i < SIZE; i ++)
hashMap.put((char) i, 0);
for (int i = 0; i < str.length(); i ++){
hashMap.put(chars[i], hashMap.get(chars[i]) + 1);
}
for (int i = 0; i < str.length(); i ++){
if (hashMap.get(chars[i]) == 1)
return String.valueOf(chars[i]);
}
return null;
}
private int index;
private int[] occurrence;
private static final int SIZE = 256;
public E50FirstNonredundantChar(){
index = 0;
occurrence = new int[SIZE];
for (int i = 0; i < SIZE; i ++)
occurrence[i] = -1;
}
public void insert(char c){
int position = (int) c;
if (occurrence[position] == -1)
occurrence[position] = index;
else if (occurrence[position] >= 0)
occurrence[position] = -2;
index ++;
}
public String getFirstNonredundantChar(){
char goalChar = '\u0000';
int minIndex = index;
for (int i = 0; i < SIZE; i ++){
if (occurrence[i] >= 0 && occurrence[i] < minIndex) {
minIndex = occurrence[i];
goalChar = (char) i;
}
}
return String.valueOf(goalChar);
}
public static void main(String[] args){
String str = "acbfweacrte";
System.out.println(E50FirstNonredundantChar.getChar(str));
E50FirstNonredundantChar first = new E50FirstNonredundantChar();
first.insert('a');
first.insert('b');
first.insert('a');
first.insert('c');
first.insert('b');
System.out.println(first.getFirstNonredundantChar());
}
}