原题链接
题目描述
在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。
示例
输入:s = "abaccdeff" 输出:'b'输入:s = "" 输出:' '
解题思路
常规思路:通过HashMap记录每一个字符出现的频率,然后遍历哈希表,遇到第一个出现一次的字符,直接返回该字符。
利用数组记录:分别给26个字母记录一个下标,然后遍历该字符串,匹配相应字符串的下标,然后让数组中出现次数+1;遍历该数组,遇到第一个出现次数为1的返回该下标对应的字符即可。
记得判空,补充边界。
代码
//HashMap
class Solution {
public char firstUniqChar(String s) {
HashMap<Character,Integer> map=new HashMap<>();
for(int i=0;i<s.length();i++){
if(!map.containsKey(s.charAt(i))){
map.put(s.charAt(i),1);
}else{
map.put(s.charAt(i),map.get(s.charAt(i))+1);
}
}
for(int i=0;i<s.length();i++){
if(map.get(s.charAt(i))==1){
return s.charAt(i);
}
}
return ' ';
}
}
//通过数组记录
class Solution {
public char firstUniqChar(String s) {
if(s.equals("")){
return ' ';
}
int []count=new int [26];
for(int i=0;i<s.length();i++){
count[s.charAt(i)-'a']++;
}
for(int i=0;i<s.length();i++){
if(count[s.charAt(i)-'a']==1){
return s.charAt(i);
}
}
return ' ';
}
}
补充
在茫茫人海中找到与自己匹配的”另一半“,当然总会有“单身狗”的存在。
哈哈哈,又是长知识的一天!!!
加油!!!