Description
面试题50. 第一个只出现一次的字符
在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。
示例:
s = “abaccdeff”
返回 “b”
s = “”
返回 “ “
限制:
0 <= s 的长度 <= 50000
Solution
这道题主要考察哈希表的用法,利用哈希表,记录每一个字符出现的次数,最后再遍历一次字符串,每次遍历都查看对应哈希表中字符出现的次数。由于题目中说明:s 只包含小写字母,所以可以利用一个长度为 26 的 char 数组。数组下标对应每一个字母 - ‘a’ 得到,小写字母的ACSII 码 - ‘a’ 可能出现的值在 [0, 25] 之间,一共 26 个小写字母。
示例代码:
class Solution {public char firstUniqChar(String s) {int[] alphabet = new int[26];for(char c: s.toCharArray()){int idx = c - 'a';alphabet[idx] ++;}char res = ' ';for(int i = 0; i < s.length(); i ++){if(alphabet[s.charAt(i)-'a'] == 1){res = s.charAt(i);break;}}return res;}}
