50 第一个只出现一次的字符
1 题目描述
在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。
示例:
s = "abaccdeff"
返回 "b"
s = ""
返回 " "
2 题目分析
两次遍历,第一次用长度为26大小的数组存储每个字符出现的次数,第二遍遍历找第一个次数为1的字符即可。
3 代码
public char firstUniqChar(String s) {
if (s == null || s.length() == 0) return ' ';
int[] words = new int[26];
Arrays.fill(words, 0);
char[] ch = s.toCharArray();
for (char c : ch) {
int idx = c - 'a';
words[idx]++;
}
for (char c : ch) {
int idx = c - 'a';
if (words[idx] == 1) return c;
}
return ' ';
}