题号:剑指 Offer 50
题目名:第一个只出现一次的字符
原题URL:https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof/
题目描述
在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。
示例
示例 1:
s = "abaccdeff"
返回 "b"
s = ""
返回 " "
限制
- 0 <= s 的长度 <= 50000
思路
1.散列表,用数组存储每个字符出现的次数
解题代码
class Solution {
public char firstUniqChar(String s) {
if(s==null||s.isEmpty()) return ' ';
char[] chars = s.toCharArray();
int[] hash = new int[26];
for (int i = 0; i < chars.length; i++) {
hash[chars[i]-'a']++;
}
for (int i = 0; i < chars.length; i++) {
if(hash[chars[i]-'a'] == 1) return chars[i];
}
return ' ';
}
}