|
| 1 | +package _20160820_1st_contest; |
| 2 | + |
| 3 | +import java.util.Comparator; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.HashSet; |
| 6 | +import java.util.Map; |
| 7 | +import java.util.Map.Entry; |
| 8 | +import java.util.PriorityQueue; |
| 9 | +import java.util.Queue; |
| 10 | +import java.util.Set; |
| 11 | + |
| 12 | +public class FirstUniqChar { |
| 13 | + public static int firstUniqChar(String s) { |
| 14 | + Map<Character, Integer> countsMap = new HashMap(); |
| 15 | + Map<Character, Integer> indexMap = new HashMap(); |
| 16 | + Set<Character> uniqSet = new HashSet(); |
| 17 | + for(int i = 0; i < s.length(); i++){ |
| 18 | + if(!countsMap.containsKey(s.charAt(i))){ |
| 19 | + countsMap.put(s.charAt(i), 1); |
| 20 | + indexMap.put(s.charAt(i), i); |
| 21 | + uniqSet.add(s.charAt(i)); |
| 22 | + } else { |
| 23 | + int currVal = countsMap.get(s.charAt(i)); |
| 24 | + countsMap.put(s.charAt(i), currVal+1); |
| 25 | + uniqSet.remove(s.charAt(i)); |
| 26 | + } |
| 27 | + } |
| 28 | + int index = Integer.MAX_VALUE; |
| 29 | + for(char c : uniqSet){ |
| 30 | + if(indexMap.get(c) < index) index = indexMap.get(c); |
| 31 | + } |
| 32 | + return (index == Integer.MAX_VALUE) ? -1 : index; |
| 33 | + } |
| 34 | + |
| 35 | + public static int firstUniqChar_dropped(String s) { |
| 36 | + //TODO: deal with extreme test case |
| 37 | + Map<Character, Integer> map = new HashMap(); |
| 38 | + //use a priorityqueue to hold all candidates, remove it from the pq once it becomes invalid |
| 39 | + Queue<Map.Entry<Character, Integer>> heap = new PriorityQueue<Map.Entry<Character, Integer>>(new Comparator<Map.Entry<Character, Integer>>(){ |
| 40 | + @Override |
| 41 | + public int compare(Entry<Character, Integer> o1, Entry<Character, Integer> o2) { |
| 42 | + if(o1.getValue() > o2.getValue()) return 1; |
| 43 | + else if(o1.getValue() < o2.getValue()) return -1; |
| 44 | + else return 0; |
| 45 | + } |
| 46 | + }); |
| 47 | + |
| 48 | + for(int i = 0; i < s.length(); i++){ |
| 49 | + if(!map.containsKey(s.charAt(i))){ |
| 50 | + map.put(s.charAt(i), 1); |
| 51 | + } else { |
| 52 | + int currVal = map.get(s.charAt(i)); |
| 53 | + map.put(s.charAt(i), currVal+1); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + for(Map.Entry<Character, Integer> e : map.entrySet()){ |
| 58 | + heap.offer(e); |
| 59 | + } |
| 60 | + |
| 61 | + while(!heap.isEmpty()){ |
| 62 | + Map.Entry<Character, Integer> curr = heap.poll(); |
| 63 | + if(map.get(curr.getKey()) > 1) continue; |
| 64 | + else return map.get(curr.getKey()); |
| 65 | + } |
| 66 | + return -1; |
| 67 | + } |
| 68 | + |
| 69 | + public static void main(String...strings){ |
| 70 | +// String s = "leetcode"; |
| 71 | +// String s = "loveleetcode"; |
| 72 | +// String s = ""; |
| 73 | + String s = "fd.fsfew@#$%d"; |
| 74 | + System.out.println(firstUniqChar(s)); |
| 75 | + } |
| 76 | +} |
0 commit comments