面试题50.第一个只出现一次的字符
题目描述
在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。
示例:
s = “abaccdeff”
返回 “b”
s = “”
返回 " "
限制:
0 <= s 的长度 <= 50000
题解1
借助双列集合HashMap,将字符串转换成字符数组后遍历字符数组并加入集合中,加入的同时,判断是否已经加入过,如果是,则将值置为2,未加入过则置1;然后遍历打印第一个值为1字符;
class Solution {
public char firstUniqChar(String s) {
HashMap<Character,Integer> hm = new HashMap<>();
char[] ch = s.toCharArray();
for(char c : ch){
if(!hm.containsKey(c)){
hm.put(c,1);
}else{
hm.put(c,2);
}
}
for(char c:ch){
if(hm.get(c)==1){
return c;
}
}
return ' ';
}
}
题解2
借助字典,将’a~z’存入字典,两次遍历,第一次将字符统计如字典数组,第二次遍历从字典获取次数,返回出现一次的字符,代码如下:
class Solution {
public char firstUniqChar(String s) {
if(s.equals("")) return ' ';
int[] ziDian = new int[26];
for(int i = 0;i<s.length();i++){
ziDian[s.charAt(i) - 'a']++;
}
for(int i = 0;i<s.length();i++){
if(ziDian[s.charAt(i) - 'a']==1)
return s.charAt(i);
}
return ' ';
}
}
提交结果
方法一:
方法二: