题目描述:
在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。
示例:
s = “abaccdeff”
返回 “b”
s = “”
返回 " "
限制:
0 <= s 的长度 <= 50000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路:
哈希+集合。根据题目要求,需要找出第一个只出现一次的字符 ,这就让我们想到了利用哈希来寻找只出现一次的字符,剩下的只需要解决该怎样定位第一个。在这里我采取先将哈希数组中值为1的字符添加到集合set中,再将所给字符串s从前往后跑一遍循环,倘若在set中,则说明这是第一个,结束循环输出。
在这里因为只有26个英文字母,我们可以通过ASCII码表来将其定位到0-25上,这样会节省时间和内存。
代码:
public class jianzhi_Offer_50 {
public char firstUniqChar(String s) {
char ans = ' ';
if(s == "")
return ans;
int[] hashnum = new int[26];
for (int i = 0 ; i < s.length(); i++){
hashnum[s.charAt(i) - 'a']++;
}
Set set = new HashSet();
for (int i = 0; i < hashnum.length; i++){
if (hashnum[i] == 1){
set.add((char) (i + 'a'));
}
}
for (int i = 0; i < s.length(); i++){
if (set.contains(s.charAt(i))){
ans = s.charAt(i);
break;
}
}
return ans;
}
public static void main(String[] args) {
jianzhi_Offer_50 obj = new jianzhi_Offer_50();
System.out.println(obj.firstUniqChar("z"));
}
}