This solution doesn't work.
public int firstUniqChar(String s) {
HashMap map = new HashMap<Character, Integer>();
for(int i = 0; i < s.length(); i++){
if(map.containsKey(s.charAt(i))){
map.put(s.charAt(i), 2);
}
else{
map.put(s.charAt(i), 1);
}
}
for(int i = 0; i < s.length(); i++){
if(map.get(s.charAt(i)) == 1){
return i;
}
}
return -1;
}
But it works now when I cast the value of the Hashmap to int
(int)map.get(s.charAt(i)) == 1
public int firstUniqChar(String s) {
HashMap map = new HashMap<Character, Integer>();
for(int i = 0; i < s.length(); i++){
if(map.containsKey(s.charAt(i))){
map.put(s.charAt(i), 2);
}
else{
map.put(s.charAt(i), 1);
}
}
for(int i = 0; i < s.length(); i++){
if((int)map.get(s.charAt(i)) == 1){
return i;
}
}
return -1;
}
I used:
System.out.print(map.get(s.charAt(i)).getClass().getName());
to confirm that the value of the map should already be an integer so I don't understand why I am getting this error when I try to submit to leetcode without casting.