Java Solution using HashMap + Array


  • 0
    A

    // algorithm: simple and brutal
    // use a HashMap to record the mapping between a char and its first index
    // use an array (same length as the string length) to record whether a char is repeated

    public class Solution {
        public int firstUniqChar(String s) {
    
            int strLen = s.length();
        
            HashMap<Character, Integer> firstIndex = new HashMap<>();
            boolean[] repeated = new boolean[strLen];
        
            for (int index = 0; index < strLen; index++) {
                char ch = s.charAt(index);
                Integer firstAppeared = firstIndex.get(ch);
                if (null == firstAppeared) {
                    firstIndex.put(ch, index);
                } else {
                    repeated[firstAppeared] = true;
                    repeated[index] = true;
                }
            }
    
            // find the first uniqueChar's index
            for (int index = 0; index < strLen; index++) {
                if (!repeated[index]) {
                    return index;
                }
            }
            return -1;
        }
    }

Log in to reply
 

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