题目描述://在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。
// 示例:
// s = "abaccdeff"
//返回 "b"
//s = ""
//返回 " "
// 限制:
// 0 <= s 的长度 <= 50000
// Related Topics 哈希表
解题思路:可以通过Hash表来解决,当hash表中已经存在该值时,存入值为fale,反正存入ture,这样遍历完字符串后,只出现一次的字符对应的值就为true,反之为fale,最后在遍历一次数组,由于遍历的字符串是有序的,当存在值为true时,直接返回的就是第一次出现一次的字符。
代码如下:
//leetcode submit region begin(Prohibit modification and deletion) class Solution { public char firstUniqChar(String s) { HashMap<Character, Boolean> map = new HashMap<>(); for(char m:s.toCharArray()){ if (map.containsKey(m)){ map.put(m,false); }else { map.put(m,true); } } for (char m:s.toCharArray()){ if (map.get(m))return m; } return ' '; } }