Description

面试题50. 第一个只出现一次的字符

在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。
示例:
s = “abaccdeff”
返回 “b”
s = “”
返回 “ “
限制:
0 <= s 的长度 <= 50000

Solution

这道题主要考察哈希表的用法,利用哈希表,记录每一个字符出现的次数,最后再遍历一次字符串,每次遍历都查看对应哈希表中字符出现的次数。由于题目中说明:s 只包含小写字母,所以可以利用一个长度为 26 的 char 数组。数组下标对应每一个字母 - ‘a’ 得到,小写字母的ACSII 码 - ‘a’ 可能出现的值在 [0, 25] 之间,一共 26 个小写字母。
示例代码:

  1. class Solution {
  2. public char firstUniqChar(String s) {
  3. int[] alphabet = new int[26];
  4. for(char c: s.toCharArray()){
  5. int idx = c - 'a';
  6. alphabet[idx] ++;
  7. }
  8. char res = ' ';
  9. for(int i = 0; i < s.length(); i ++){
  10. if(alphabet[s.charAt(i)-'a'] == 1){
  11. res = s.charAt(i);
  12. break;
  13. }
  14. }
  15. return res;
  16. }
  17. }