关于leetcode:leetcode哈希表之第一个只出现一次的字符

6次阅读

共计 688 个字符,预计需要花费 2 分钟才能阅读完成。

本文次要记录一下 leetcode 哈希表之第一个只呈现一次的字符

题目

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

s = "abaccdeff"
返回 "b"

s = ""返回" "

 

限度:0 <= s 的长度 <= 50000

起源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。

题解

class Solution {public char firstUniqChar(String s) {if (s == null || s.length() == 0) {return ' ';}
        Map<Character, Integer> map = new LinkedHashMap<>();
        char[] arr = s.toCharArray();
        for (Character e : arr) {Integer count  = map.get(e);
            if (count == null) {map.put(e, 1);
            } else {map.put(e, count + 1);
            }
        }

        for(Map.Entry<Character,Integer> entry : map.entrySet()) {if (entry.getValue() == 1) {return entry.getKey();
            }
        }

        return ' ';
    }
}

小结

这里借助 LinkedHashMap 来计数,最初按程序遍历,找出 count 为 1 的失去第一个只呈现一次的字符。

doc

  • 第一个只呈现一次的字符
正文完
 0