Leetcode刷题之旅--剑指 Offer 50. 第一个只出现一次的字符

tech2022-11-01  124

题目描述:

思路:最暴力的方法–先遍历一遍,用map存储。之后再按照字符串顺序遍历一遍,并查看map存储的数值。 可以用有序的LinkedHashMap来对第二次遍历进行优化。另外,map存储出现次数可以使用boolean来节省空间。

class Solution { public char firstUniqChar(String s) { char[] word=s.toCharArray(); Map<Character,Boolean> map=new LinkedHashMap<>(); for(int i=0;i<word.length;i++){ map.put(word[i],map.containsKey(word[i])); } for(Map.Entry<Character,Boolean>d:map.entrySet()){ if(!d.getValue())return d.getKey(); } return ' '; } }
最新回复(0)