剑指 Offer . 第一个只出现一次的字符(3.31)
题目描述:
在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。
示例 1:
s = "abaccdeff"
返回 "b"
s = ""
返回 " "
解题思路:
面对一个字符串,判断里面单的字符,首先要想到转换成字符数组,挨个遍历其中的字符。然后根据hashmap的特点不能存储重复元素,所以遍历的过程将字符作为key往hashmap 中添加,如果有重复,在value中标记,最后再遍历得到value中第一个被标记的元素,返回他的key值
具体代码:
class Solution {
public char firstUniqChar(String s) {
HashMap<Character, Boolean> hm = new HashMap<>();
for(char c :s.toCharArray()){
hm.put(c,hm.containsKey(c));
}
for(char s1 :s.toCharArray()){
if(!hm.get(s1)){
return s1;
}
}
return ' ';
}
}