Java O (n) solution counting frequency using HashMap


  • 0
    M

    Just counting the frequency of letter and throwing into a HashMap, then on the second loop the first character that has count of 1 is the index to be returned.

    public class Solution {
        
        public int firstUniqChar(String s) {
            
            if (s.length() == 1) return 0;
            char[] value = s.toCharArray();
            Map<Character, Integer> map = new HashMap<>();
            
            for (int i = 0; i < value.length; i++) {
                Integer count = map.get(value[i]);
                if (count == null) count = new Integer(1);
                else count++;
                map.put(value[i], count);
            }
            
            for (int j = 0; j < value.length; j++) {
                if (map.get(value[j]).equals(1)) return j;
            }
            
            return -1;   
        }
        
    }
    

Log in to reply
 

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