Java solution using hashmap


  • 0
    J

    '''
    public class Solution {
    public int firstUniqChar(String s) {
    if (s == null || s.length() == 0) return -1;
    Map<Character, Integer> map = new HashMap<Character, Integer>();
    for (int i = 0; i < s.length(); i++) {
    if (map.containsKey(s.charAt(i))) {
    map.put(s.charAt(i), map.get(s.charAt(i))+1);
    } 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;
    }
    }
    '''


Log in to reply
 

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