First Unique Character in a String


  • 0
    F
        public int firstUniqChar(String input) {
            if (input.length() == 0 || input == null){
                return -1;
            }
            HashMap<Character,Integer> charAndCount = new HashMap<Character,Integer>();
            char c;
            for (int i = 0;i<input.length();i++) {
                c = input.charAt(i);
                if (charAndCount.containsKey(c)) {
                    charAndCount.put(c, charAndCount.get(c) + 1);
                } else {
                    charAndCount.put(c, 1);
                }
            }
            for (int i = 0; i<input.length();i++){
                c = input.charAt(i);
                if (charAndCount.get(c).equals(1)){
                    return i;
                }
            }
            if (!charAndCount.containsValue(1)){
                return -1;
            }
            return 0;
        }
    }```

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.