Java double Hashtable solution (92 ms)


  • 0
    H

    Not very efficient but I thought it was fun

    import java.util.Hashtable;
    public class Solution {
        public int firstUniqChar(String s) {
            Hashtable<Character,Integer> tableOnce = new Hashtable<Character,Integer>();
            Hashtable<Character,Integer> tableTwice = new Hashtable<Character,Integer>();
            char[] charArray = s.toCharArray();
            
            //store in the hashtables 
            for (int i = 0;i < charArray.length;i++) {
                if (tableOnce.containsKey(charArray[i]))
                    tableTwice.put(charArray[i],i);
                else 
                    tableOnce.put(charArray[i],i);
            }
            
            
            //check which one occurs once
            for (int i = 0;i < charArray.length;i++) {
                if (!tableTwice.containsKey(charArray[i]))
                    return tableOnce.get(charArray[i]);
            }
            
            return -1;
        }
    

    }```


Log in to reply
 

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