第一个只出现一次的字符

 

在字符串 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

class Solution {
    public char firstUniqChar(String s) {
        if(s==null) return ' ';
        int fren[]=new int[26];
        for(int i=0;i<s.length();i++)
            fren[s.charAt(i)-'a']++;
        
        for(int i=0;i<s.length();i++)
            if(fren[s.charAt(i)-'a']==1)
            return s.charAt(i);
        
        return ' ';
    }
}

解题思路:由于题目给出了一个条件( s 只包含小写字母。)所以可以利用数组将26个字母全部存储,每一个索引从a--z一一对应;

之后再次遍历字符串,找到所有字符中只出现一次的字母,返回即可。

 

很多人用的都是哈希表解题,这题的初衷也是训练有关哈希表的理解,我这里使用数组只是帮助自己对哈希表理解起来简单点而已。

posted on 2020-08-02 16:44  九七97  阅读(195)  评论(0编辑  收藏  举报

导航