Thursday, July 14, 2016

Find firstNon repeating character in string in one pass

import java.util.LinkedHashMap;
public class FirstNonRepeated {
    public static void main(String[] args) {
        LinkedHashMap<Character, Integer> linkedHashMap = new LinkedHashMap<>();
        String str = "allergicToBitches";
        for (int i = 0; i < str.length(); i++) {
            char key = str.charAt(i);
            if (linkedHashMap.containsKey(key)) {
                linkedHashMap.remove(key);
            } else {
                Integer val = linkedHashMap.get(key);
                linkedHashMap.put(key, null == val ? 1 : val + new Integer(1));
            }
        }
        System.out.print(linkedHashMap.entrySet().iterator().next().getKey());
    }
}