本文主要记录一下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的获得第一个只出现一次的字符。code