LeetCode:387. 字符串中的第一个唯一字符(Java)

题目:

解答:

用一个LinkedHashMap实现,key为字母,value如果第一次插入存入索引,再次插入存-1,然后遍历HashMap,找到第一个不是-1的value(LinkedHashMap保证了插入顺序,所以找到的一定是第一个唯一字符)。

class Solution {
    public int firstUniqChar(String s) {
        Map<Character, Integer> sCount = new LinkedHashMap<Character, Integer>();
        for (int i = 0; i < s.length(); i++) {
            char letter = s.charAt(i);
            if (sCount.containsKey(letter)) {
                sCount.put(letter, -1);
            }
            else {
                sCount.put(letter, i);
            }
        }
        Iterator iter = sCount.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<Character, Integer> entry = (Map.Entry)iter.next();
            if (entry.getValue() == -1) {
                continue;
            }
            return entry.getValue();
        }
        return -1;
    }
}

具体到这个题目,由于这里只有小写字母且ASCII码是连续的,于是可以把数组当作hash表用:

class Solution {
    public int firstUniqChar(String s) {
        int[] count = new int[26];
        for (int i = 0; i < s.length(); i++) {
            count[s.charAt(i) - 'a']++;
        }
        for (int i = 0; i < s.length(); i++) {
            if (count[s.charAt(i) - 'a'] == 1) {
                return i;
            }
        }
        return -1;
    }
}

参考:https://leetcode.com/problems/first-unique-character-in-a-string/discuss/86348/Java-7-lines-solution-29ms

猜你喜欢

转载自blog.csdn.net/SoulOH/article/details/81508994