原题(来源Leetcode)
在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。
示例:
s = "abaccdeff" 返回 "b" s = "" 返回 " "
限制:
0 <= s 的长度 <= 50000
解法
思想
既然是第一个只出现一次的字符,我觉得可以用LinkedHashMap,Entries是自然按照插入顺序排序的,遍历的时候也好找。
代码
class Solution {
public char firstUniqChar(String s) {
Map<Character,Integer> counts = new LinkedHashMap<>();
for(char i:s.toCharArray()){
counts.put(i,counts.getOrDefault(i,0)+1);
}
Set<Map.Entry<Character,Integer>> entries = counts.entrySet();
for(Map.Entry<Character,Integer> entry:entries){
if(entry.getValue() == 1) return entry.getKey();
}
return ' ';
}
}
原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/%e5%89%91%e6%8c%87offer50-%e7%ac%ac%e4%b8%80%e4%b8%aa%e5%8f%aa%e5%87%ba%e7%8e%b0%e4%b8%80%e6%ac%a1%e7%9a%84%e5%ad%97%e7%ac%a6/