美文网首页
387. First Unique Character in a

387. First Unique Character in a

作者: Super_Alan | 来源:发表于2018-05-09 14:54 被阅读0次

    LeetCode Link

    public int firstUniqChar(String s) {
        LinkedHashMap<Character, Integer> uniqMap = new LinkedHashMap<>();
        Set<Character> 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<Map.Entry<Character, Integer>> iter = uniqMap.entrySet().iterator();
        return iter.hasNext() ? iter.next().getValue() : -1;
    }
    
    public int firstUniqChar(String s) {
        LinkedHashMap<Character, Integer> 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<Map.Entry<Character, Integer>> iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<Character, Integer> entry = iter.next();
            if (entry.getValue() >= 0) {
                return entry.getValue();
            }
        }
    
        return -1;
    }
    

    相关文章

      网友评论

          本文标题:387. First Unique Character in a

          本文链接:https://www.haomeiwen.com/subject/ilonrftx.html