First Unique Character in a String - JAVA Linkedhashmap


  • 0
    C

    import java.util.LinkedHashMap;

    class Solution {
    public int firstUniqChar(String s) {

        char[] chars = s.toCharArray();
        LinkedHashMap ocurrs = new LinkedHashMap();
        if (chars.length == 1) {
           // System.out.println("case - 1");
            return 0;
        }
        
        for (int i=0;i<(chars.length);i++) {
           if (ocurrs.get(chars[i]) == null) {
               ocurrs.put(chars[i],-1);
           } else {
               ocurrs.put(chars[i], 1);
           }
            
        }
        
        Set result = ocurrs.keySet();
        Iterator it = result.iterator();
        while(it.hasNext()) {
            char key = (char) it.next();
            int value = (int) ocurrs.get(key);
            if (value == -1) {
                return s.indexOf(key); 
            }
        }
        
        return -1;
        
    }
    

    }


Log in to reply
 

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