387. First Unique Character in a String

LeetCode Link

public int firstUniqChar(String s) {
    LinkedHashMap uniqMap = new LinkedHashMap<>();
    Set dupSet = new HashSet<>();
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (dupSet.contains(c)) {
            continue;
        } else if (uniqMap.containsKey(c)) {
            uniqMap.remove(c);
            dupSet.add(c);
        } else {
            uniqMap.put(c, i);
        }
    }

    Iterator> iter = uniqMap.entrySet().iterator();
    return iter.hasNext() ? iter.next().getValue() : -1;
}
public int firstUniqChar(String s) {
    LinkedHashMap map = new LinkedHashMap<>();
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (!map.containsKey(c)) {
            map.put(c, i);
        } else {
            map.put(c, -1);
        }
    }

    Iterator> iter = map.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry entry = iter.next();
        if (entry.getValue() >= 0) {
            return entry.getValue();
        }
    }

    return -1;
}

你可能感兴趣的:(387. First Unique Character in a String)