跳至主要內容

50-第一个只出现一次的字符

daipeng小于 1 分钟

在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。

输入:s = "abaccdeff"
输出:'b'

思路很简单,遍历,统计字符出现的次数,然后返回第一个出现次数为1的字符即可。注意需要使用LinkedHashMap,用来保证顺序。

 public char firstUniqChar(String s) {
        if (s == null || s.equals(" ")) {
            return ' ';
        }
        char[] chs = s.toCharArray();

        Map<Character, Integer> data = new LinkedHashMap<>();
        for (char ch : chs) {
            data.merge(ch, 1, Integer::sum);
        }
        for (Map.Entry<Character, Integer> entry : data.entrySet()) {
            if (entry.getValue() == 1) {
                return entry.getKey();
            }
        }
        return ' ';
    }